You are here
Formatting currency in Java with String.format
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.
// %, => local-specific thousands separator // .2f => positions after decimal point } @Test void formattingOfBigDecimalToString() { assertEquals("23.356,00", formattedPrice); formattedPrice = formatCurrency(priceToFormat); assertEquals("3.245,90", formattedPrice); formattedPrice = formatCurrency(priceToFormat); assertEquals("89.645,99", formattedPrice); formattedPrice = formatCurrency(priceToFormat); assertEquals("989.645,99", formattedPrice); formattedPrice = formatCurrency(priceToFormat); assertEquals("1.230.490,00", formattedPrice); formattedPrice = formatCurrency(priceToFormat); assertEquals("1.230.490,01", formattedPrice); }
Sources
Category: