# number（x）或parseFloat（x）哪个更好？

2020/11/09 13:22 · javascript ·  · 0评论

## parseFloat和Number之间的区别

`parseFloat`/`parseInt`用于解析字符串，而`Number`/`+`用于将值强制转换为数字。他们的行为有所不同。但首先让我们看看它们的行为相同：

``````parseFloat('3'); // => 3
Number('3'); // => 3
parseFloat('1.501'); // => 1.501
Number('1.501'); // => 1.501
parseFloat('1e10'); // => 10000000000
Number('1e10'); // => 10000000000
``````

``````parseFloat('1x'); // => 1
Number('1x'); // => NaN
``````

``````parseFloat('0x10'); // => 0
Number('0x10'); // => 16
``````

``````parseFloat(''); // => NaN
Number(''); // => 0
parseFloat(' \r\n\t'); // => NaN
Number(' \r\n\t'); // => 0
``````

``````Number('0x10'); // => 16
+'0x10'; // => 16
Number('10x'); // => NaN
+'10x'; // => NaN
Number('40'); // => 40
+'40'; // => 40
``````

``````Number("") === 0               // also holds for false
isNaN(parseFloat("")) === true // and null

isNaN(Number("32f")) === true
parseFloat("32f") === 32
``````

``````Number('') = 0;
Number(false) = 0;
Number('1a') = NaN;

parseFloat('') = NaN;
parseFloat(false) = NaN;
parseFloat('1a') = 1;
``````

parseFloat会慢一些，因为它会搜索字符串中数字的首次出现，而Number构造函数会从包含带空格的数字值或包含假值的字符串中创建一个新的数字实例。

PS：如果您对某些通用类型转换解决方案感兴趣，可以在我的博客中阅读有关类型转换的文章：http//justsimplejs.blogspot.com/2012/08/data-type-conversion.html

`+""``Number("")`返回0，而`parseFloat("")`返回NaN。

As far as I know, and this is only overheard from colleagues so might be entirely ill informed, that parseFloat is marginally faster.

Though on further researching, it would seem that this performance difference is browser dependant.

http://jsperf.com/parseint-vs-parsefloat/6

Have a look at these jsPerf results, and make you're call. (it includes +x tests as well)

As noted in @xdazz 's answer, `+""` and `Number("")` return `0` while `parseFloat("")` returns `NaN` so Again I would go with parseFloat, because an empty string does NOT mean the number 0, only a string with the character `"0"` in it means 0;