I would like to convert a floating point variable to a string without losing any precision.
I.e. I would like the string to have the same information as my floating point variable contains, since I use the output for further processing (even if it means that the string will be very long and readable).
To put this more clearly, I would like to have functions for cyclic conversion
var dA = 323423.23423423e4;
var sA = toString(dA);
var dnA = toDouble(sA);
and I would like dnA and dA to be equal
Thanks
PS: Sources on the internet usually talk about how to round strings but I have not found information on exact representation. Also I am not interested in Arbitrary Precision calculations, I just need double precision floating point arithmetic.
Let string arithmetic do the string conversion, and then use parseFloat to get it back to a float:
var dA = 323423.23423423e4;
var sA = dA + '';
var dnA = parseFloat(sA);
Here's a fiddle to see it in action.
Note: All JavaScript numbers are doubles, so you don't need to draw a distinction between doubles and floats. Thus, the only place you'd need to worry about precision loss is in your first line. For example, if you did var dA = 987654321.0123456789 for your first line, it would be equivalent to var dA = 987654321.01234567, and dA would still equal dnA in the end.
Just dA.toString() and parseFloat(sA) should do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With