Mastodon

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.

void formatCurrency(BigDecimal value) {
 
	// %,  => local-specific thousands separator
	// .2f => positions after decimal point
 
	return String.format("%,.2f", price);
}
 
@Test
void formattingOfBigDecimalToString() {
 
	BigDecimal priceToFormat = BigDecimal.valueOf(23356);
	String formattedPrice = formatCurrency(priceToFormat);
	assertEquals("23.356,00", formattedPrice);
 
	priceToFormat = BigDecimal.valueOf(3245.9);
	formattedPrice = formatCurrency(priceToFormat);
	assertEquals("3.245,90", formattedPrice);
 
	priceToFormat = BigDecimal.valueOf(89645.99);
	formattedPrice = formatCurrency(priceToFormat);
	assertEquals("89.645,99", formattedPrice);
 
	priceToFormat = BigDecimal.valueOf(989645.99);
	formattedPrice = formatCurrency(priceToFormat);
	assertEquals("989.645,99", formattedPrice);
 
	priceToFormat = BigDecimal.valueOf(1230490);
	formattedPrice = formatCurrency(priceToFormat);
	assertEquals("1.230.490,00", formattedPrice);
 
	priceToFormat = BigDecimal.valueOf(1230490.01);
	formattedPrice = formatCurrency(priceToFormat);
	assertEquals("1.230.490,01", formattedPrice);
}

Sources