Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java's DecimalFormat for "smart" currency formatting?

I'd like to use Java's DecimalFormat to format doubles like so:

#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41

The best I can come up with so far is:

new DecimalFormat("'$'0.##");

But this doesn't work for case #2, and instead outputs "$100.5"

Edit:

A lot of these answers are only considering cases #2 and #3 and not realizing that their solution will cause #1 to format 100 as "$100.00" instead of just "$100".

like image 450
Peter Avatar asked Feb 17 '11 19:02

Peter


People also ask

What is number format and DecimalFormat class?

Class DecimalFormat. DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits.

What is the decimal format?

The "D" (or decimal) format specifier converts a number to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. This format is supported only for integral types. The precision specifier indicates the minimum number of digits desired in the resulting string.


2 Answers

Does it have to use DecimalFormat?

If not, it looks like the following should work:

String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
//Handle the weird exception of formatting whole dollar amounts with no decimal
currencyString = currencyString.replaceAll("\\.00", "");
like image 190
Bradley Swain Avatar answered Oct 10 '22 14:10

Bradley Swain


Use NumberFormat:

NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
double doublePayment = 100.13;
String s = n.format(doublePayment);
System.out.println(s);

Also, don't use doubles to represent exact values. If you're using currency values in something like a Monte Carlo method (where the values aren't exact anyways), double is preferred.

See also: Write Java programs to calculate and format currency

like image 7
Alexandra Dumas Avatar answered Oct 10 '22 15:10

Alexandra Dumas