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

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

当前回答

比较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

其他回答

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”。

对于浮动

var decimal=  /^[-+]?[0-9]+\.[0-9]+$/; 

if (!price.match(decimal)) {
      alert('Please enter valid float');
      return false;
    }

对于整数

var number = /^\d+$/; 

if (!price.match(number)) {
      alert('Please enter valid integer');
      return false;
    }

我们可以通过isInteger函数进行检查。ie number将返回true,float返回false

console.log(Number.isIInteger(2)),<BR>将返回true

console.log(Number.isInteger(2.5))将返回false

这是检查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;   
}   

试试这个

let n;
return (n = value % 1) !== 0 && !isNaN(n);

当返回值为false时,表示输入值为浮点数或浮点数字符串,否则输入值为整数numref或整数字符串。

基本上,它需要检查精度值是否不等于零。

另一个是检查正确的字符串编号。