3

I have a 64-bit long containing an IEEE 754 representation of a double. I'd like to convert it to a string just like the standard Java Double.toString(d) does. However, I can't use any of the methods of the Double class, because they are buggy. (String.valueOf(d) and "" + d don't work either, because they use Double.toString(d) internally. NumberFormat doesn't work, because it loses precision.) So I need pure Java code which would do the conversion.

Where can I find such code? I tried the source code of GNU Classpath, but it uses a native method for this conversion.

pts
  • 80,836
  • 20
  • 110
  • 183

1 Answers1

5

I searched a bit and I found that: dtoa.java. It seems complicated, but the code is under the GPL license (or the Mozilla Public License 1.1 license).

I hope it will help you.

(I even found the bug you refer to.)

Edit:

[Andrew Thompson] is right, you often (always?) lose precision with floating point. As pointed here, you might want to use BigDecimal

Community
  • 1
  • 1
fstamour
  • 760
  • 4
  • 9
  • Thank you for finding dtoa.java for me, I've just +1ed your answer. Ugh, it's indeed complicated. – pts Aug 01 '12 at 23:41
  • Well, you didn't see the [http://www.netlib.org/fp/dtoa.c](`C version`)... It has a lot and a lot of prepocessor directives. – fstamour Aug 01 '12 at 23:45
  • 1
    No, we don't always lose precision with floating point, e.g. with IEEE 754, if the numbers are 50-bit integers, then calculations are exact. But that's not the typical case. In the typical case, there is a loss of precision. – pts Aug 02 '12 at 14:28