Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure Java code to convert an IEEE 754 double to string

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.

like image 423
pts Avatar asked Feb 18 '26 05:02

pts


1 Answers

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

like image 78
fstamour Avatar answered Feb 20 '26 18:02

fstamour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!