Formatting currency in Java with String.format


Posted by Steven

There are common tasks in programming I never performed in a production project. Formatting currency is one of them. I only noticed that when I searched a library that would offer formatting methods. After searching for a while and wondering why so many libraries exist, a colleague found a surprisingly easy solution: String.format(). Here is some code to show how to format currency with plain Java.

  1. void formatCurrency(BigDecimal value) {
  2.  
  3. // %, => local-specific thousands separator
  4. // .2f => positions after decimal point
  5.  
  6. return String.format("%,.2f", price);
  7. }
  8.  
  9. @Test
  10. void formattingOfBigDecimalToString() {
  11.  
  12. BigDecimal priceToFormat = BigDecimal.valueOf(23356);
  13. String formattedPrice = formatCurrency(priceToFormat);
  14. assertEquals("23.356,00", formattedPrice);
  15.  
  16. priceToFormat = BigDecimal.valueOf(3245.9);
  17. formattedPrice = formatCurrency(priceToFormat);
  18. assertEquals("3.245,90", formattedPrice);
  19.  
  20. priceToFormat = BigDecimal.valueOf(89645.99);
  21. formattedPrice = formatCurrency(priceToFormat);
  22. assertEquals("89.645,99", formattedPrice);
  23.  
  24. priceToFormat = BigDecimal.valueOf(989645.99);
  25. formattedPrice = formatCurrency(priceToFormat);
  26. assertEquals("989.645,99", formattedPrice);
  27.  
  28. priceToFormat = BigDecimal.valueOf(1230490);
  29. formattedPrice = formatCurrency(priceToFormat);
  30. assertEquals("1.230.490,00", formattedPrice);
  31.  
  32. priceToFormat = BigDecimal.valueOf(1230490.01);
  33. formattedPrice = formatCurrency(priceToFormat);
  34. assertEquals("1.230.490,01", formattedPrice);
  35. }

Sources

Category: 
Share: