How can I format a String number to have commas and round?(如何将字符串数字格式化为逗号和四舍五入?)
问题描述
将以下数字格式化为字符串的最佳方法是什么?
What is the best way to format the following number that is given to me as a String?
String number = "1000500000.574" //assume my value will always be a String
我希望这是一个字符串,其值为:1,000,500,000.57
I want this to be a String with the value: 1,000,500,000.57
我怎样才能这样格式化它?
How can I format it as such?
推荐答案
你可能想看看 DecimalFormat 类;它支持不同的语言环境(例如:在某些国家/地区会被格式化为 1.000.500.000,57).
您还需要将该字符串转换为数字,这可以通过以下方式完成:
You also need to convert that string into a number, this can be done with:
double amount = Double.parseDouble(number);
代码示例:
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
这篇关于如何将字符串数字格式化为逗号和四舍五入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将字符串数字格式化为逗号和四舍五入?
基础教程推荐
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
