« FOSS and OASIS When Spyware (authors) Strike Back »
Another Day, Another JVM Bug
Posted February 23, 2005 – 3:00 pm by Yakov Shafranovich in ProgrammingI am not 100% sure if it is a bug, but the consensus within my company seems to indicate that it is. Here is a copy of the bug report filed with Sun:
synopsis: DecimalFormat with a Lot of “#” Returns Incorrect Results for Floats
FULL PRODUCT VERSION :
java version “1.5.0″
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0-b64)
Java HotSpot(TM) Client VM (build 1.5.0-b64, mixed mode)
ADDITIONAL OS VERSION INFORMATION :
Redhat Fedora Core 2 / Linux 2.6.10-1.9_FC2 #1 i686 athlon i386 GNU/Linux
A DESCRIPTION OF THE PROBLEM :
When using DecimalFormat with a lot of “#”, putting too many “#” causes conversion problems with floats. For example, using “############0.0#######” on “0.3f” will produce “0.30000001″ instead of “0.3″. Converting the float to string first via “String test = “” + 0.3f” doesn’t have this problem. Doesn’t happen with doubles.
STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
DecimalFormat df = new DecimalFormat(”############0.0#######”);
System.out.println(df.format(0.3f));
ACTUAL -
0.30000001
REPRODUCIBILITY :
This bug can be reproduced always.
---------- BEGIN SOURCE ---------- import java.text.DecimalFormat; public class DecimalFormatTester { public static void main(String[] args) { DecimalFormat df1 = new DecimalFormat("#0.0#"); DecimalFormat df2 = new DecimalFormat("############0.#######"); float test_value = 0.3f; System.out.println("Short: " + df1.format(test_value)); System.out.println("Long: " + df2.format(test_value)); } } ---------- END SOURCE ----------CUSTOMER SUBMITTED WORKAROUND :
Use “#0.0#” instead.
Permalink | Trackback URL | This post has














