开发者

How can I check to see if a value is a float in javascript [duplicate]

This question already has answers here: 开发者_Python百科 How do I check that a number is float or integer? (51 answers) Closed 8 years ago.

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 function
  • isNaN
  • 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜