How can I check to see if a value is a float in javascript [duplicate]
I want to check to see if my input is a float.
Sooo something like...
if (typeof (input) == "float")
do something....
What is the proper way to do this?
Try parseFloat
The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.
if(!isNaN(parseFloat(input))) {
// is float
}
As spraff said, you can check the type of an input with typeof
. In this case
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?
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
:
input = Number(input);
if (!isNaN(input)) {
// It was already a number or we were able to convert it
}
More:
Number
called as a functionisNaN
parseFloat
typeof foo === "number"
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).
精彩评论