tags:

views:

145

answers:

4

how to find if a number is float or integer?

1.25 --> float  
1 --> integer  
0 --> integer  
0.25 --> integer
+1  A: 

Try this.

function isFloat (n) {
  return n===+n && n!==(n|0);
}

function isInteger (n) {
  return n===+n && n===(n|0);
}
no
only works if a number is passed
John Hartsock
heh awesom exploit, it's pretty much mine (`n===+n` to check for numeric, `n|0` to round), but with built-in operators. funky
Claudiu
@John Hartsock a string is never going to be a numeric value. It's a string. The point of this function is to test whether a value is a Javascript numeric value that has no fractional part and is within the size limits of what can be represented as an exact integer. If you want to check a string to see if it contains a sequence of characters that represent a number, you'd call `parseFloat()` first.
Pointy
@Pointy but parseFloat("1.1a") will still return 1.1. Suppose you had a text field you wanted to validate that it was an float and only a float without alpha characters. Testing weather a text field from an input element for decimal(float)
John Hartsock
@John Hartsock: it won't return true unless a number primitive was passed. I think that makes sense given the names of the functions. Anything else should be a candidate for isString, isBoolean, etc. if such functions are being written.
no
A: 

As others mentioned, you only have doubles in JS. So how do you define a number being an integer? Just check if the rounded number is equal to itself:

function isInteger(f) {
    return typeof(f)==="number" && Math.round(f) == f;
}
function isFloat(f) { return typeof(f)==="number" && !isInteger(f); }
Claudiu
Might want to check that the value is numeric... `isFloat('abc')` returns `true`
no
ah yes good point
Claudiu
+1  A: 

It really depends on what you want to achieve. If you want to "emulate" strongly typed languages then I suggest you not trying. As others mentioned all numbers have the same representation (the same type).

Using something like Claudiu provided:

isInteger( 1.0 ) -> true

which looks fine for common sense, but in something like C you would get false

galambalazs
A: 

check a remainder when dividing by 1:

function isInt(n){
   return n%1==0
}

If you don't know that the argument is a number-

function isInt(n){
   return typeof n== 'number' && n%1==0
}
kennebec
simple n efficient solution.
coure06
Careful, this will also return true for an empty string, a string representing an integral number, `true`, `false`, `null`, an empty array, an array containing a single integral number, an array containing a string representing an integral number, and maybe more.
no