Skip to main content

Bug in java.text.DecimalFormat

2 replies [Last post]
nitinchauhan
Offline
Joined: 2004-11-07
Points: 0

Hi !

For following code :

java.text.DecimalFormat df = new java.text.DecimalFormat("0.0",new java.text.DecimalFormatSymbols(java.util.Locale.US));
df.setMaximumFractionDigits(1);
System.out.println(df.format(1.15));
System.out.println(df.format(1.25));
System.out.println(df.format(1.35));
System.out.println(df.format(1.45));
System.out.println(df.format(1.55));

I expected following output :
1.2
1.3
1.4
1.5
1.6

But the output in JRE 1.6.0-beta and 1.4.1_07 is:
1.2
1.2
1.4
1.4
1.6

is this known bug ? or the correct behaviour ?

Thanks

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
nitinchauhan
Offline
Joined: 2004-11-07
Points: 0

Hi Naoto,

Thank you very much for quick clarification and the solution :)

Nitin

njs
Offline
Joined: 2004-03-11
Points: 0

Hi nitinchauhan,

Yes, that's the correct behavior because the rounding mode of the DecimalFormat class is ROUND_HALF_EVEN (http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html#ROUND_...).

From JDK 1.6, NumberFormat class provides a new method called setRoundingMode() in which you can specify your favorite rounding modes. If you want the result in your post, you may want to issue one of the following call depending on your need:

df.setRoundingMode(RoundingMode.UP);
df.setRoundingMode(RoundingMode.CEILING);
df.setRoundingMode(RoundingMode.HALF_UP);

Hope this helps.
Naoto