如何格式化字符串数字以包含逗号和四舍五入? [英] How can I format a String number to have commas and round?

查看:25
本文介绍了如何格式化字符串数字以包含逗号和四舍五入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

格式化作为字符串提供给我的以下数字的最佳方法是什么?

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

我该如何格式化?

推荐答案

您可能需要查看 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));

这篇关于如何格式化字符串数字以包含逗号和四舍五入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆