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

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

问题描述

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

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

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

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