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

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

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

10条回答
  •  没有蜡笔的小新
    2020-11-22 12:40

    parseInt() -> Parses a number to specified redix.

    Number()-> Converts the specified value to its numeric equivalent or NaN if it fails to do so.

    Hence for converting some non-numeric value to number we should always use Number() function.

    eg.

    Number("")//0
    parseInt("")//NaN
    
    Number("123")//123
    parseInt("123")//123
    
    Number("123ac") //NaN,as it is a non numeric string
    parsInt("123ac") //123,it parse decimal number outof string
    
    Number(true)//1
    parseInt(true) //NaN
    

    There are various corner case to parseInt() functions as it does redix conversion, hence we should avoid using parseInt() function for coersion purposes.

    Now, to check weather the provided value is Numeric or not,we should use nativeisNaN() function

提交回复
热议问题