javascript Number(...) 和 parseFloat(...) 有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11988547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:58:40  来源:igfitidea点击:

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

javascriptstring-conversion

提问by Naftali aka Neal

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

JavaScript 中的 parseInt(string) 和 Number(string)什么区别之前已经问过了。

But the answers basically focused on the radixand the ability of parseIntto take a string like "123htg"and turn it into 123.

但答案基本上集中在radix和能力parseInt采取像绳子"123htg",把它变成123

What I am asking here is if there is any big difference between the returns of Number(...)and parseFloat(...)when you pass it an actual number stringwith no radix at all.

我在这里要问的是Number(...)parseFloat(...)当你传递一个没有基数的实际数字字符串时,它的返回值和返回值之间是否有什么大的区别。

采纳答案by James Allardice

No. Both will result in the internal ToNumber(string)function being called.

否。两者都会导致ToNumber(string)调用内部函数。

From ES5 section 15.7.1(The Number Constructor Called as a Function):

来自ES5 第 15.7.1 节(作为函数调用的数字构造函数):

When Numberis called as a function rather than as a constructor, it performs a type conversion...

Returns a Number value (not a Number object) computed by ToNumber(value)if value was supplied, else returns +0.

Number作为函数而不是构造函数调用时,它执行类型转换...

返回一个 Number 值(不是 Number 对象),ToNumber(value)如果提供了 value,则返回+0

From ES5 section 15.1.2.3(parseFloat (string)):

来自ES5 第 15.1.2.3 节(parseFloat (string)):

... If neither trimmedStringnor any prefix of trimmedStringsatisfies the syntax of a StrDecimalLiteral(see 9.3.1) ...

... 如果既不满足trimmedString也不trimmedString满足任何前缀的 a StrDecimalLiteral(见 9.3.1) ...

And 9.3.1is the section titled "ToNumber Applied to the String Type", which is what the first quote is referring to when it says ToNumber(value).

9.3.1是名为“ToNumber应用在String类型”的部分,这是第一次报价是指当它说ToNumber(value)



Update(see comments)

更新(见评论)

By calling the Numberconstructor with the newoperator, you will get an instance of the Numberobject, rather than a numeric literal. For example:

通过Number使用new运算符调用构造函数,您将获得Number对象的实例,而不是数字文字。例如:

typeof new Number(10); //object
typeof Number(10); //number

This is defined in section 15.7.2(The Number Constructor):

这在第 15.7.2 节(数字构造函数)中定义:

When Numberis called as part of a newexpression it is a constructor: it initialises the newly created object.

Number作为new表达式的一部分被调用时,它是一个构造函数:它初始化新创建的对象。

回答by KooiInc

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 Numberthat will not succeed. As in:

正如@James Allardic 已经回答的那样,内部运作并没有什么不同。不过还是有区别的。使用parseFloat,以一个或多个数字字符开头,后跟字母数字字符的(修剪的)字符串可以转换为数字,Number但不会成功。如:

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

回答by Elias Van Ootegem

Not a whole lot of difference, as long as you're sure there's nothing but digits in your string. If there are, Numberwill return NaN.
Another problem that you might get using the Numberconstructor is that co-workers might think you forgot the newkeyword, and add it later on, causing strict comparisons to fail new Number(123) === 123--> false whereas Number(123) === 123--> true.

只要您确定字符串中只有数字,就没有太大区别。如果有,Number将返回NaN
使用Number构造函数可能会遇到的另一个问题是,同事可能认为您忘记了new关键字,并在稍后添加它,导致严格比较失败new Number(123) === 123--> false 而Number(123) === 123--> true。

In general, I prefer to leave the Numberconstructor for what it is, and just use the shortest syntax there is to castto an int/float: +numString, or use parse*.

在一般情况下,我宁愿离开Number它是什么构造,只是用最短的语法有以为int /浮动:+numString或使用parse*

回答by Hymanwanders

When not using newto create a wrapper object for a numerical value, Numberis relegated to simply doing type conversion from string to number.

当不new用于为数值创建包装对象时,Number被降级为简单地进行从字符串到数字的类型转换。

'parseFloat' on the other hand, as you mentioned, can parse a floating point number from any string that starts with a digit, a decimal, or +/-

另一方面,正如您所提到的,'parseFloat' 可以从以数字、小数或 +/- 开头的任何字符串中解析浮点数

So, if you're only working with strings that contain only numerical values, Number(x)and parseFloat(x)will result in the same values

所以,如果你只处理只包含数值的字符串,Number(x)并且parseFloat(x)会产生相同的值

回答by ahains

Please excuse me posting yet another answer, but I just got here via a Google search and did not find all of the details that I wanted. Running the following code in Node.js:

请原谅我发布了另一个答案,但我刚刚通过谷歌搜索来到这里,并没有找到我想要的所有细节。在 Node.js 中运行以下代码:

var vals = ["1", "1.1", "0", "1.1abc", "", " ", null];
for(var i = 0; i < vals.length; i++){
  var ifTest = false;
  if(vals[i])
  {
    ifTest = true;
  }
  console.log("val=" + vals[i] + ", Number()=" + Number(vals[i])+ ", parseFloat()=" + parseFloat(vals[i]) + ", if()=" + ifTest);
}

gives the following output:

给出以下输出:

val=1, Number()=1, parseFloat()=1, if()=true
val=1.1, Number()=1.1, parseFloat()=1.1, if()=true
val=0, Number()=0, parseFloat()=0, if()=true
val=1.1abc, Number()=NaN, parseFloat()=1.1, if()=true
val=, Number()=0, parseFloat()=NaN, if()=false
val= , Number()=0, parseFloat()=NaN, if()=true
val=null, Number()=0, parseFloat()=NaN, if()=false

Some noteworthy takeaways:

一些值得注意的要点:

  1. If protecting with an if(val) before trying to convert to number, then parseFloat() will return a number except in the whitespace case.
  2. Number returns a number in all cases except for non-numeric characters aside from white-space.
  1. 如果在尝试转换为数字之前使用 if(val) 进行保护,则 parseFloat() 将返回一个数字,除了空格情况。
  2. Number 在所有情况下都返回一个数字,除了空格之外的非数字字符。

Please feel free to add any test cases that I may be missing.

请随时添加我可能遗漏的任何测试用例。