JavaScript中判断为整数的多种方式,以及保留两位小数

方式一、使用取余运算符判断

任何整数都会被1整除,即余数是0。利用这个规则来判断是否是整数。

1

2

3

4

5

function isInteger(obj) {

    return obj%1 === 0

}

isInteger(3) // true

isInteger(3.3) // false  

以上输出可以看出这个函数挺好用,但对于字符串和某些特殊值显得力不从心

1

2

3

4

isInteger(''// true

isInteger('3'// true

isInteger(true// true

isInteger([]) // true

 

对于空字符串、字符串类型数字、布尔true、空数组都返回了true,真是难以接受。对这些类型的内部转换细节感兴趣的请参考:JavaScript中奇葩的假值

 

因此,需要先判断下对象是否是数字,比如加一个typeof

1

2

3

4

5

6

7

function isInteger(obj) {

    return typeof obj === 'number' && obj%1 === 0

}

isInteger(''// false

isInteger('3'// false

isInteger(true// false

isInteger([]) // false

嗯,这样比较完美了。

 

二、使用Math.round、Math.ceil、Math.floor判断

整数取整后还是等于自己。利用这个特性来判断是否是整数,Math.floor示例,如下

1

2

3

4

5

6

7

8

9

function isInteger(obj) {

    return Math.floor(obj) === obj

}

isInteger(3) // true

isInteger(3.3) // false

isInteger(''// false

isInteger('3'// false

isInteger(true// false

isInteger([]) // false

这个直接把字符串,true,[]屏蔽了,代码量比上一个函数还少。

 

三、通过parseInt判断

1

2

3

4

5

6

7

8

9

function isInteger(obj) {

    return parseInt(obj, 10) === obj

}

isInteger(3) // true

isInteger(3.3) // false

isInteger(''// false

isInteger('3'// false

isInteger(true// false

isInteger([]) // false

很不错,但也有一个缺点

1

isInteger(1000000000000000000000) // false

竟然返回了false,没天理啊。原因是parseInt在解析整数之前强迫将第一个参数解析成字符串。这种方法将数字转换成整型不是一个好的选择。

 

四、通过位运算判断

1

2

3

4

5

6

7

8

9

function isInteger(obj) {

    return (obj | 0) === obj

}

isInteger(3) // true

isInteger(3.3) // false

isInteger(''// false

isInteger('3'// false

isInteger(true// false

isInteger([]) // false

这个函数很不错,效率还很高。但有个缺陷,上文提到过,位运算只能处理32位以内的数字,对于超过32位的无能为力,如

1

isInteger(Math.pow(2, 32)) // 32位以上的数字返回false了

当然,多数时候我们不会用到那么大的数字。

 

五、ES6提供了Number.isInteger

1

2

3

4

5

6

Number.isInteger(3) // true

Number.isInteger(3.1) // false

Number.isInteger(''// false

Number.isInteger('3'// false

Number.isInteger(true// false

Number.isInteger([]) // false

 

目前,最新的Firefox和Chrome已经支持。

 

js 输入int类型数字后自动在后面加.00

 var getFloatStr = function (num) {
      num += '';
      num = num.replace(/[^0-9|\.]/g, ''); //清除字符串中的非数字非.字符

      if (/^0+/) //清除字符串开头的0
          num = num.replace(/^0+/, '');
      if (!/\./.test(num)) //为整数字符串在末尾添加.00
          num += '.00';
      if (/^\./.test(num)) //字符以.开头时,在开头添加0
          num = '0' + num;
      num += '00';        //在字符串末尾补零
      num = num.match(/\d+\.\d{2}/)[0];
      return num;
  };

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值