Skip to content Skip to sidebar Skip to footer

Facing An Issue With Parsefloat When Input Is More Than 16 Digits

I am facing weird issued. parseFloat(11111111111111111) converts it to 11111111111111112. I noticed that it works fine till length is 16 but rounds off higher when input length is

Solution 1:

Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.

More information here

Solution 2:

Numbers in javascript are represented using 64 bit floating point values (so called doubles in other languages).

doubles can hold at most 15/16 significant digits (depends on number magnitute). Since range of double is 1.7E+/-308 some numbers can only be aproximated by double, in your case 11111111111111111 cannot be represented exactly but is aproximated by 11111111111111112 value. If this sounds strange then remember that 0.3 cannot be represented exactly as double too.

double can hold exact integers values in range +/-2^53, when you are operating in this range - you may expect exact values.

Solution 3:

Javascript has a constant, Number.MAX_SAFE_INTEGER which is the highest integer that can be exactly represented.

Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect.

The value is 9007199254740991 (2^53 - 1) which makes a maximum of 15 digits safe.

Solution 4:

BigInt is a built-in object that provides a way to represent whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent with the Number primitive.

BigInt can be used for arbitrarily large integers.

Solution 5:

As you can see in the following blog post, JavaScript only supports 53 bit integers.

if you type in the console var x = 11111111111111111 and then type x you'll get 11111111111111112 This has nothing to do with the parseFloat method.

There's also a related question here about working with big numbers in JavaScript.

Post a Comment for "Facing An Issue With Parsefloat When Input Is More Than 16 Digits"