How can I format a String number to have commas and round? How can I format a String number to have commas and round? java java

How can I format a String number to have commas and round?


You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).

You also need to convert that string into a number, this can be done with:

double amount = Double.parseDouble(number);

Code sample:

String number = "1000500000.574";double amount = Double.parseDouble(number);DecimalFormat formatter = new DecimalFormat("#,###.00");System.out.println(formatter.format(amount));


This can also be accomplished using String.format(), which may be easier and/or more flexible if you are formatting multiple numbers in one string.

    String number = "1000500000.574";    Double numParsed = Double.parseDouble(number);    System.out.println(String.format("The input number is: %,.2f", numParsed));    // Or    String numString = String.format("%,.2f", numParsed);

For the format string "%,.2f" - "," means separate digit groups with commas, and ".2" means round to two places after the decimal.

For reference on other formatting options, see https://docs.oracle.com/javase/tutorial/java/data/numberformat.html


Once you've converted your String to a number, you can use

// format the number for the default localeNumberFormat.getInstance().format(num)

or

// format the number for a particular localeNumberFormat.getInstance(locale).format(num)