Java:使用逗号格式化数字

huangapple go评论67阅读模式
英文:

Java: Format Numbers with commas

问题

只要将数字以“易读”的格式输出即可。例如,可以将100000输出为100.000,这样更容易阅读。

是否已经存在可用于此目的的方法?

英文:

I just want the numbers to be output in "well readable" format. e.g. you can output 100000 as 100.000 which would be more readable.

Is there an already existing method that can be used for this?

答案1

得分: 7

你可以使用NumberFormat

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

输出:

100,000
英文:

You can use NumberFormat:

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

Output:

100,000

答案2

得分: 0

你可以使用 DecimalFormatJava 7+):

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

输出:

100.000

DecimalFormat 拥有更多的灵活性,可以通过模式将数字转换为字符串。

英文:

You can use DecimalFormat (Java 7+):

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

output:

100.000

DecimalFormat has more flexibility to convert numbers to string by pattern.

huangapple
  • 本文由 发表于 2020年8月30日 19:21:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/63656883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定