如何将字符串数字格式化为逗号和四舍五入?

将以下数字格式化为字符串的最佳方法是什么?

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));

相关文章