
An easy way to output currency in Java is to use the built-inNumberFormat class. This lets you format a number like1000.2399
for output as$1,000.24
.
NumberFormat rounds to two decimals, adds necessary commas, and includes a$
in front.
To use NumberFormat, import the class at the top of your program:
importjava.text.NumberFormat;
Next, create the NumberFormat object and assign it to a variableformatter
:
NumberFormatformatter=NumberFormat.getCurrencyInstance();
Finally, use theformatter
object to invoke theformat()
method on the amount to be formatted:
doubleamt=1000.2399;StringamtFormatted=formatter.format(amt);
Note that the result is aString
value.
Here is a full program example:
importjava.text.NumberFormat;publicclassNumberFormatExample{publicstaticvoidmain(String[]args){NumberFormatformatter=NumberFormat.getCurrencyInstance();doubleamt=1000.2399;StringamtFormatted=formatter.format(amt);System.out.println("original: "+amt);System.out.println("formatted: "+amtFormatted);}}
Here is the output:
original: 1000.2399formatted: $1,000.24
Follow me on Twitter@realEdwinTorres
for more programming tips and help.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse