Java: Format Numbers with commas

Viewed 1268

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?

2 Answers

You can use NumberFormat:

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

Output:

100,000

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.

Related