What is the difference between parseInt() and Number()?

前端 未结 10 905
無奈伤痛
無奈伤痛 2020-11-22 12:02

How do parseInt() and Number() behave differently when converting strings to numbers?

10条回答
  •  时光取名叫无心
    2020-11-22 12:19

    Its a good idea to stay away from parseInt and use Number and Math.round unless you need hex or octal. Both can use strings. Why stay away from it?

    parseInt(0.001, 10)
    0
    
    parseInt(-0.0000000001, 10)
    -1
    
    parseInt(0.0000000001, 10)
    1
    
    parseInt(4000000000000000000000, 10)
    4
    

    It completly butchers really large or really small numbers. Oddly enough it works normally if these inputs are a string.

    parseInt("-0.0000000001", 10)
    0
    
    parseInt("0.0000000001", 10)
    0
    
    parseInt("4000000000000000000000", 10)
    4e+21
    

    Instead of risking hard to find bugs with this and the other gotchas people mentioned, I would just avoid parseInt unless you need to parse something other than base 10. Number, Math.round, Math.foor, and .toFixed(0) can all do the same things parseInt can be used for without having these types of bugs.

    If you really want or need to use parseInt for some of it's other qualities, never use it to convert floats to ints.

提交回复
热议问题