What is the difference between Number(…) and parseFloat(…)

前端 未结 5 1430
Happy的楠姐
Happy的楠姐 2020-12-05 18:04

What is the difference between parseInt(string) and Number(string) in JavaScript has been asked previously.

But the answers basically focused on the radix

5条回答
  •  鱼传尺愫
    2020-12-05 18:35

    The internal workings are not that different, as @James Allardic already answered. There is a difference though. Using parseFloat, a (trimmed) string starting with one or more numeric characters followed by alphanumeric characters can convert to a Number, with Number that will not succeed. As in:

    parseFloat('3.23abc'); //=> 3.23
    Number('3.23abc'); //=> NaN
    

    In both conversions, the input string is trimmed, by the way:

    parseFloat('  3.23abc '); //=> 3.23
    Number('   3.23 '); //=> 3.23
    

提交回复
热议问题