Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Float has a rounding limit? How can I fix this?

I set up a system that parses a compact data string into JSON. I'm using a 19 digit number to store ids. Unfortunately any number greater than 17 digits, parseFloat() rounds the last few digits.

This breaks the whole data string. Can I fix this?

For example 8246295522085275215 gets turned into 8246295522085276000. Why is this?

http://jsfiddle.net/RobertWHurst/mhZ7Q/

like image 912
Robert Hurst Avatar asked Nov 02 '11 23:11

Robert Hurst


People also ask

What does parse float mean?

parseFloat() The parseFloat() function parses a string argument and returns a floating point number.

What is a floating point number in JavaScript?

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63: Value (aka Fraction/Mantissa)

How does JavaScript parseFloat work?

parseFloat() method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns NaN .


2 Answers

JavaScript has only one numeric type, which is an IEEE 754 double precision floating-point. That means, you have a maximum of 52 bits of precision, which is a bit more than 15 decimal places.

If you need more precision than that, you have to use a bignum library or work with strings.

like image 132
Michael Borgwardt Avatar answered Sep 28 '22 02:09

Michael Borgwardt


Numbers in JavaScript lose precision if they are higher than a certain value.

According to http://www.hunlock.com/blogs/The_Complete_Javascript_Number_Reference, integers are only reliable up to 15 digits (9 * 10^15 to be exact).

like image 22
ThiefMaster Avatar answered Sep 28 '22 00:09

ThiefMaster