ParseInt () scientific notation

I played with JS and noticed it.

Why parseInt(1e+21) return 1 and parseInt(1e+20) return 100000000000000000000 ? parseInt(10e+20) also returns 1 ?

Why parseInt(1.7976931348623157E+10308); returns NaN , and parseFloat(1.7976931348623157E+10308) returns Infinity ?


I even made a Fibonacci sequence, and any value that has +21 exponents returns only the first digit:

fibonacci sequence scientific notation

parseFloat() will return the correct number ad infinitum.

Fibonacci demo (int: parseInt (): parseFloat ())

(tested in Chrome)

+5
source share
1 answer

parseInt and parseFloat should parse strings and convert them to Number s. So, when you pass them a Number , it gets a forced interpretation. So, at least in Firefox, "" + 1e+20 displays "100000000000000000000" , and "" + 1e+21 displays "1e+21" .

Let's read the parseInt documentation :

If parseInt encounters a character that is not a digit in the specified radius, it ignores it and all subsequent characters and returns an integer value processed to this point

therefore parseInt("1.whatever") returns 1 and parseInt("32.231e+something") returns 32.

A similar thing should happen with parseFloat .

This is a weak input error. IMO the correct behavior when doing what you are doing is an exception.

+3
source

Source: https://habr.com/ru/post/1215522/


All Articles