parseInt() parses number literals with exponent incorrectly

后端 未结 6 1396
慢半拍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:53

    parseInt(-3.67394039744206e-15) === -3

    The parseInt function expects a string as the first argument. JavaScript will call toString method behind the scene if the argument is not a string. So the expression is evaluated as follows:

    (-3.67394039744206e-15).toString()
    // "-3.67394039744206e-15"
    parseInt("-3.67394039744206e-15")
    // -3
    

    -3.67394039744206e-15.toFixed(19) === -3.6739e-15

    This expression is parsed as:

    • Unary - operator
    • The number literal 3.67394039744206e-15
    • .toFixed() -- property accessor, property name and function invocation

    The way number literals are parsed is described here. Interestingly, +/- are not part of the number literal. So we have:

    // property accessor has higher precedence than unary - operator
    3.67394039744206e-15.toFixed(19)
    // "0.0000000000000036739"
    -"0.0000000000000036739"
    // -3.6739e-15
    

    Likewise for -3.67394039744206e-15.toFixed(2):

    3.67394039744206e-15.toFixed(2)
    // "0.00"
    -"0.00"
    // -0
    

提交回复
热议问题