Skip to main content

Formating BigDecimal: bug in java.util.Formatter?

No replies
mitok71
Offline
Joined: 2009-05-26

Hi,

I formate a BigDecimal value with String formater and get problems with it.

this line throws an exception
return String.format("%,.1f", new java.math.BigDecimal("0.0011"));

java.lang.IllegalArgumentException: Digits < 0
at java.math.MathContext.(Unknown Source)
at java.math.MathContext.(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter$FormatSpecifier.printFloat(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)

To reproduce it the precision of BigDecimal must be at least 2 digits more as in format string and the length of precision in format string plus 2 chars must be 0.
It would work with:
return String.format("%,.1f", new java.math.BigDecimal("0.0111"));
but not any more with
return String.format("%,.2f", new java.math.BigDecimal("0.0001"));

The workaround is simple:
return String.format("%,.2f", new java.math.BigDecimal("0.0001").floatValue());
it works for me since i don't have very big precision.

But i think it could be a BUG in JRE.

I have tested with JRE 1.6.0_07 and 1.6.0_13-b03

I don't know how i could report it. Or is it enough to post it just here in forum?

regards
Dmitri