Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  46] [ 4]  / answers: 1 / hits: 17798  / 12 Years ago, fri, december 7, 2012, 12:00:00

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.


More From » javascript

 Answers
8

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.


[#81544] Thursday, December 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnathanhakeems

Total Points: 487
Total Questions: 129
Total Answers: 100

Location: Fiji
Member since Fri, Nov 13, 2020
4 Years ago
;