简体   繁体   English

Java:用逗号格式化数字

[英]Java: Format Numbers with commas

I just want the numbers to be output in "well readable" format.我只希望数字为“可读性”格式的 output。 eg you can output 100000 as 100.000 which would be more readable.例如,您可以将 output 100000 作为 100.000,这将更具可读性。

Is there an already existing method that can be used for this?是否已经存在可用于此的方法?

You can use NumberFormat :您可以使用NumberFormat

int n = 100000;
String formatted = NumberFormat.getInstance().format(n);
System.out.println(formatted);

Output: Output:

100,000

You can use DecimalFormat ( Java 7+ ):您可以使用DecimalFormat ( Java 7+ ):

var dfs = new DecimalFormatSymbols();
dfs.setGroupingSeparator('.');
var df = new DecimalFormat("###,##0", dfs);
System.out.println(df.format(100000));

output: output:

100.000

DecimalFormat has more flexibility to convert numbers to string by pattern. DecimalFormat在按模式将数字转换为字符串方面具有更大的灵活性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM