What is the best way to format the following number that is given to me as a String?
String number = "1000500000.574" //assume my value will always be a String
I want this to be a String with the value: 1,000,500,000.57
How can I format it as such?
The first answer works very well, but for ZERO / 0 it will format as .00
Hence the format #,##0.00 is working well for me. Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.
you can also use below solution -
Here is the simplest way to get there:
output: 10,987,655.88
You can do the entire conversion in one line, using the following code:
The last two # signs in the DecimalFormat constructor can also be 0s. Either way works.
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.
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