如何检查值是否为 javascript 中的浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6900646/
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
How can I check to see if a value is a float in javascript
提问by Dennis Martinez
I want to check to see if my input is a float.
我想检查一下我的输入是否是浮点数。
Sooo something like...
Sooo之类的...
if (typeof (input) == "float")
do something....
What is the proper way to do this?
这样做的正确方法是什么?
回答by naveen
Try parseFloat
尝试 parseFloat
The parseFloat()function parses an argument (converting it to a string first if needed) and returns a floating point number.
所述parseFloat()函数解析参数(其转换为第一,如果需要的字符串),并返回一个浮点数。
if(!isNaN(parseFloat(input))) {
// is float
}
回答by spraff
All numbers are floats in Javascript. Note that the type name is in quotes, it's a string, and it's all lower case. Also note that typeof
is an operator, not a function, no need for parens (though they're harmless).
所有数字都是 Javascript 中的浮点数。请注意,类型名称在引号中,它是一个字符串,并且都是小写的。另请注意,这typeof
是一个运算符,而不是一个函数,不需要括号(尽管它们是无害的)。
回答by T.J. Crowder
As spraff said, you can check the type of an input with typeof
. In this case
正如 spraff 所说,您可以使用typeof
. 在这种情况下
if (typeof input === "number") {
// It's a number
}
JavaScript just has Number
, not separate float
and integer
types. More about figuring out what things are in JavaScript: Say what?
JavaScript 只有Number
,而不是单独的float
和integer
类型。更多关于弄清楚 JavaScript 中的内容:说什么?
If it may be something else (like a string) but you want to convert it to a number if possible, you can use either Number
or parseFloat
:
如果它可能是其他东西(如字符串)但您想尽可能将其转换为数字,则可以使用Number
或parseFloat
:
input = Number(input);
if (!isNaN(input)) {
// It was already a number or we were able to convert it
}
More:
更多的: