如何发现一个数字是浮点数或整数?

1.25 --> float  
1 --> integer  
0 --> integer  
0.25 --> float

当前回答

function int(a) {
  return a - a === 0 && a.toString(32).indexOf('.') === -1
}

function float(a) {
  return a - a === 0 && a.toString(32).indexOf('.') !== -1
}

如果要排除字符串,可以添加类型a==“number”。

其他回答

这是检查INT和FLOAT的最终代码

function isInt(n) { 
   if(typeof n == 'number' && Math.Round(n) % 1 == 0) {
       return true;
   } else {
       return false;
   }
} 

OR

function isInt(n) {   
   return typeof n == 'number' && Math.Round(n) % 1 == 0;   
}   

比较floor()结果与ceil()结果不同。

const isFloat = v => Math.floor(v) !== Math.ceil(v);
> isFloat(1)
= false

> isFloat(1.1)
= true

> isFloat(42)
= false

> isFloat(84.42)
= true

YourJS提供了以下两个函数,这些函数适用于所有数字,包括为Infinity和Infinity返回false:

function isFloat(x) {
  return typeOf(x, 'Number') && !!(x % 1);
}

function isInt(x) {
  return typeOf(x, 'Number') && x % 1 == 0;
}

由于typeOf()是一个YourJS内部函数,如果你想使用这些定义,你可以在这里下载这些函数的版本:http://yourjs.com/snippets/build/34

为什么不这样做:

var isInt = function(n) { return parseInt(n) === n };

这真的取决于你想要实现什么。如果你想“模仿”强类型语言,那么我建议你不要尝试。正如其他人提到的,所有数字都有相同的表示(相同类型)。

使用Claudiu提供的内容:

isInteger(1.0)->true

这看起来很正常,但在C这样的情况下,你会错