3

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?

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Dennis Martinez
  • 6,344
  • 11
  • 50
  • 67

3 Answers3

14

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    
}
naveen
  • 53,448
  • 46
  • 161
  • 251
  • 1
    what if I pass integer instead of float in input? – Shivek Parmar Mar 01 '16 at 08:31
  • `!Number.isInteger(val)` - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger or see the “already has answers here” link at the top of this page – MrColes Oct 01 '20 at 18:36
  • @MrColes: your comment is wrong on this context. OP has specifically asked how to identify a float. `!Number.isInteger('lorem ipsum')` returns true too. As MDN notes, *The Number.isInteger() method determines whether the passed value is an **integer**.* – naveen Oct 01 '20 at 23:24
  • parseFloat("2A") return 2, which is not NaN, so this is not correct. – thienDX Oct 23 '20 at 09:25
  • @thienDX: 2A is a hexadecimal number. MDN notes, *For radices above 10, letters of the English alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.* – naveen Oct 26 '20 at 16:21
  • @naveen it's was not a good example. parseFloat("2Z") also return 2 – thienDX Oct 27 '20 at 04:25
3

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:

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

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).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
spraff
  • 32,570
  • 22
  • 121
  • 229