How can I represent monetary values in Java? Should I use double or float?

Byron Tymvios

To represent monetary values in Java you should use the BigDecimal class. Using double or float might result in loss of precision as they have rounding differences, which is not ideal when dealing with money. BigDecimal also offers methods for mathematical calculations like add, subtract, multiply and divide so no operators are necessary.

To display the values of BigDecimal you can use a combination of NumberFormat and BigDecimal:

BigDecimal bd = new BigDecimal(12345.45d);
String sFormatted = NumberFormat.getCurrencyInstance().format(bd.doubleValue());
System.out.println("The formatted number: " + sFormatted);

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact