forty4seven
forty4seven

Reputation: 73

Java: Format Numbers with commas

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?

Upvotes: 4

Views: 4599

Answers (2)

kozmo
kozmo

Reputation: 4471

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.

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28414

You can use NumberFormat:

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

Output:

100,000

Upvotes: 8

Related Questions