【问题标题】:How to differentiate between a one-decimal float and integer in JavaScript如何区分 JavaScript 中的一位十进制浮点数和整数
【发布时间】:2015-11-19 12:50:48
【问题描述】:

我正在使用一个函数来验证作为参数传递的数字是 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)); 返回浮点数。

【问题讨论】:

标签: javascript types floating-point integer decimal


【解决方案1】:

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

因此,没有跨浏览器的方式来保证:

3
3.0
3.0000000000000

等等。

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

试图在 JS 中强制转换或强制数字类型安全是毫无意义的。
处理数字格式的数字,根据需要使用所需的精度转换成字符串和字符串。

【讨论】:

    【解决方案2】:

    我不相信这是可能的,除非您可以在值变成数字之前访问该值的字符串表示形式。 JavaScript 会丢弃这些信息。

    您要解决什么问题才能保证这种差异化?

    【讨论】:

    • 这是在课堂上提出的问题。我只是想知道是否有可能做到这一点。
    【解决方案3】:

    一个简单的解决方案: 检查数字和整数版本相除的余数是否为0。

    if(x % parseInt(x) == 0) 
         return 'integer';
     else return 'float';
    

    【讨论】:

    • 或者只是if(x === parseInt(x)) :)
    【解决方案4】:

    试试这个

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

    【讨论】:

    • 不幸的是,这不起作用,因为x.toString() 不会保留.0
    • 明白了!似乎是不可能真正做到的事情。
    【解决方案5】:

    也许如果你改变输入,然后比较改变做了什么?

    沿着这条线,(当然可以以某种方式简化)例如:

    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
    }

    【讨论】:

      【解决方案6】:

      我想我找到了一个更简单且有效的解决方案:

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

      这会“锁定”数字,因此 JavaScript 不允许将数字四舍五入,使其小于 nr。您在括号中指定的小数位数。

      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。
      猜你喜欢
      • 1970-01-01
      • 2010-09-22
      • 2015-09-12
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      相关资源
      最近更新 更多