Why do some floating point numbers appear with a trailing 0
Asked Answered
L

2

20

Does anyone know why the numbers 0.001 to 0.009 are rendered to a String with a trailing 0 but other numbers do not. e.g. numbers 0.01 to 0.09 do not.

System.out.println(Locale.getDefault());
for (int i = 0; i <= 20; i++)
    System.out.println(i / 1e3);

prints

en_GB
0.0
0.0010
0.0020
0.0030
0.0040
0.0050
0.0060
0.0070
0.0080
0.0090
0.01
0.011
0.012
0.013
0.014
0.015
0.016
0.017
0.018
0.019
0.02

EDIT The code for DecimalFormat doesn't appear to be locale dependant. If I run

for (Locale l : Locale.getAvailableLocales())   {
    Locale.setDefault(l);
    System.out.println(l + " " + 1 / 1e3);
}

on Java 6 update 26 on Ubuntu 11.04 I get

ja_JP 0.0010
es_PE 0.0010
en 0.0010
... many locales with the same result ...
sv_SE 0.0010
da_DK 0.0010
es_HN 0.0010

on Java 7 on same system I get

ms_MY 0.001
ar_QA 0.001
is_IS 0.001
... many locales with the same result ...
el_CY 0.001
hu 0.001
fr_FR 0.001
Lice answered 27/9, 2011 at 5:19 Comment(8)
Hmm... I don't get that behaviour. I get "0.001" etc. What locale are you in?Paratrooper
I am getting this behaviour, fr_CH, but I get it with Locale.US as well.Lanlana
May be the JVM, I'm using Windows7 jdk 1.6.22Lanlana
@Matthew: Interesting. I'm using JDK 7 on Windows 7, btw.Paratrooper
same as @JonSkeet with Ubuntu 10.10, JDK 1.6.0_20Jitter
The DecimalFormat class doesn't appear to be locale dependant. This happens with Java 6 update 26, but not Java 7 on Ubuntu 11.04Lice
I get same as Peter, en_AU, java version "1.6.0_24" Java(TM) SE Runtime Environment (build 1.6.0_24-b07) Java HotSpot(TM) Client VM (build 19.1-b02, mixed mode, sharing)Wordbook
I don't get trailing zeroes with JDK 7 on Win XP with locale Locale loc = Locale.forLanguageTag("hi"); Locale.setDefault(loc);. EDIT: I also don't get it for en_US. EDIT 2: As a matter of fact, I don't get trailing zeroes for any locale.Burny
T
13

This was identified as a bug in Java 1.3 - Java 6: http://bugs.java.com/view_bug.do?bug_id=4428022

EDIT: As to why this happens, here's the fix referred to in the bug report that was ported from OpenJDK 6: http://hg.openjdk.java.net/jdk6/jdk6/jdk/rev/8159687b6316

Turns out it's an off-by-one error. (The fix changes <= to <).

Tented answered 27/9, 2011 at 5:53 Comment(2)
A bug it appears it took them ten years to fix. :PLice
Tracked down the patch that fixed this (info added to the answer).Tented
B
4

For those interested, here is a diff between the FloatingDecimal class responsible for creating the string representation of the double. As you can see from the diff, the patch fixes the special case encountered when the exponent is -3 in the dtoa() method.

Burny answered 27/9, 2011 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.