parseInt() parses number literals with exponent incorrectly

后端 未结 6 1383
慢半拍i
慢半拍i 2021-01-17 13:48

I have just observed that the parseInt function doesn\'t take care about the decimals in case of integers (numbers containing the e character).

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-17 13:57

    If the parsed string (stripped of +/- sign) contains any character that is not a radix digit (10 in your case), then a substring is created containing all the other characters before such character discarding those unrecognized characters.

    In the case of -3.67394039744206e-15, the conversion starts and the radix is determined as base 10 -> The conversion happens till it encounters '.' which is not a valid character in base 10 - Thus, effectively, the conversion happens for 3 which gives the value 3 and then the sign is applied, thus -3.

    For implementation logic - http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.2

    More Examples -

    alert(parseInt("2711e2", 16));
    alert(parseInt("2711e2", 10));

    TO note:

    The radix starts out at base 10.

    If the first character is a '0', it switches to base 8.

    If the next character is an 'x', it switches to base 16.

提交回复
热议问题