How to format a BigDecimal without losing trailing fraction zeros?

116 Views Asked by At

NumberFormat doesn't seem to care about the scale of a BigDecimal, so given tailing zeros are lost:

NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
nf.setMaximumFractionDigits(Integer.MAX_VALUE);

BigDecimal a = new BigDecimal("1234.56789");  //scale=5
BigDecimal b = new BigDecimal("1234.567890"); //scale=6
a.toString(); //1234.56789
b.toString(); //1234.567890 <-- ✅ decimal place is preserved

nf.format(a); //1.234,56789
nf.format(b); //1.234,56789 <-- ❌ decimal place is lost
2

There are 2 best solutions below

2
Knight Industries On

Unless there is a better way:

synchronized (nf) {
  nf.setMinimumFractionDigits(number.scale());
  nf.format(number); //1.234,567890 <-- ✅ decimal place is preserved
}
1
worpet On

NumberFormat will predictably format a number into a consistent readable value. It uses the exact format rules you set for it.

The only format rules you have set are to start with the rules for the German Local and to include no more than Integer.MAX_VALUE (2,147,483,647) decimal places.

NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
nf.setMaximumFractionDigits(Integer.MAX_VALUE);

The above rules do not include anything to output trailing decimal zeros, the formatter will simply output the number concisely. If you were to format the numbers 1234.56789, 1234.567890, or 1234.567890000000000, they would all consistently output "1.234,56789" since, unless specified otherwise, the default way to format numbers in German is to use . as the thousands separator, , as the decimal separator, and to not include any leading or trailing zeros.

To see a minimum number of decimal places, you would need to specifically set this number with setMinimumFractionDigits.