如何在JavaScript中区分一位小数和整数

3
我正在使用一个函数来验证参数传递的数字在JavaScript中是浮点数还是整数。
该方法适用于像'4.34'这样具有非零小数的数字,但对于像'3.0'这样的数字失败了,返回整数而不是浮点数。
以下是我目前能够想出的代码。
function dataType(x) {
    if (typeof x === 'number' && ){
        if (Math.round(x) === x ){
            return 'integer';
        }
        return 'float';
    }
}

console.log(dataType(8)); //integer
console.log(dataType(3.01)); //float
console.log(dataType(3.0)); // should return float

我希望能得到JavaScript的相关帮助。
提前感谢您。

更新内容:我希望console.log(dataType(3.0));返回浮点类型。


http://stackoverflow.com/questions/10590973/check-if-input-is-float-or-integer - SaggingRufus
7个回答

5

JavaScript中的每个数字都是浮点数。JS中只有一种数字类型(Number)。

因此,在不同浏览器之间无法保证以下这些值的区别:

3
3.0
3.0000000000000

等等。

即使在现代浏览器中,(3.0000).toString( ) === "3"; //true

试图在JS中进行数字类型转换或强制类型安全性是相当无意义的。
使用Number格式处理数字,并根据需要将其转换为字符串,以达到所需的精度。


2
我不认为这是可能的,除非您可以访问在值变成数字之前的字符串表示。JavaScript会丢弃此信息。
您试图解决什么问题,需要进行这种区分吗?

这是课堂上提出的一个问题。我只想知道是否有可能完成这个任务。 - kevgathuku

1
一个简单的解决方案: 检查将数字除以其整数版本的余数是否为0。
if(x % parseInt(x) == 0) 
     return 'integer';
 else return 'float';

或者只需要这样写:if(x === parseInt(x)) :) - tikej

0

试一下

function dataType(x) {
    if (typeof x === 'number' ){
        if (Math.round(x) === x && x.toString().indexOf('.') < -1 ){
            return 'integer';
        }
        return 'float';
    }
}

很遗憾,这不起作用,因为 x.toString() 无法保留 .0 - ryachza
搞定!似乎有些事情是真正不可能做到的。 - dburgess923

0

我认为我已经找到了一个更简单且有效的解决方案:

使用Number.prototype.toFixed()函数。

这将“锁定”数字,使JavaScript无法将数字四舍五入为小于括号中指定的小数位数。

let int = 1
let float = 1.0;

console.log( "WARNING: toFixed() returns a: ", typeof float.toFixed(2) ); // string

console.log( "NOTICE: float is still a: ", typeof float ) // float

console.log( int === float , "<--- that is an incorrect result");
console.log( int.toString() === float.toFixed(1) ) // correct result here
console.log( int.toString() == float.toFixed(1) )
console.log( int.toString())
console.log( float.toFixed(1))

// You can "lock" the float variable like this:
float = float.toFixed(1);
// but now float is a: string
console.log( 'NOTICE: the "locked" float is now a: ', typeof float )
console.log( "and that will crash any future atempts to use toFixed() bacause that function does not exist on strings, only on numbers.");
console.log( "Expected crash here: " )
float.toFixed(1)


不行!如果 int=1.0,它仍然会报告它们是不同的,因为 toString() 会将其四舍五入为 1,而 toFixed() 则完全不会对其进行四舍五入。同时,toFixed() 还会添加 "必需" 的尾随零,如果一个数字太短,则这些字符串将与彼此有所不同,并因此报告为 false。 - Sebastian Norr

0
也许如果您更改输入并比较更改的内容呢?
类似这样的东西,(它肯定可以以某种方式简化)例如:

function isFloat(x){ // example: x = 3.00 or x = 3.99

  if( typeof x === 'number' ){

      var obj = {};
      obj.ceil = false;
      obj.floor = false;
      obj.round = false;

      if( Math.ceil(x+0.1) === x ){
        obj.ceil = true;
      }
      if(Math.floor(x+0.1) === x ){
        obj.floor = true;
      }
      if (Math.round(x) === x ){
          obj.round = true;
      }

      if( obj.round == true){ // or use obj.floor?
        return "integer";
      }
      if( (obj.floor == true) && (obj.round == true) ) { // either && or || not sure
        return 'float';
      }
    }
}

通过使用例如3.00和3.99这些值,我们可以得到这些“配置文件”,可用于识别数字(类似于指纹):
(需要使用更多数字类型进行额外测试(我只使用笔和纸测试了这两个数字),但我认为这有效)

isFloat(3.00){
  ceil  is false
  floor is true
  round is true
}

isFloat(3.99){
  ceil  is false
  floor is false
  round is false
}


0

JS 中的每个数字都是浮点数。在 JS 中只有一种数字类型(Number)。

But if u want the def u can find it like this

function dataType(x) {
    if (typeof x === 'number' ){
        if (x.toString().indexOf('.') > -1 ){
            return 'integer';
        }
        return 'float';
    }
}

console.log(dataType(5.3)) // float
console.log(dataType(5)) // int


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接