JS49 判断整数类型和直接取整的方法

判断整数的方法

1 利用parseInt

const isInteger(target) =>  parseInt(target) === target

注意,parseInt只会返回两个类型的结果,数值或者NaN

2 利用取余运算

const isInteger(target) => typeof target === 'number' && target % 1 === 0

3 利用Math方法

const isInteger(target) => Math.round(target) === target;
const isInteger(target) => Math.ceil(target) === target;
const isInteger(target) => Math.floor(target) === target

4 利用按位运算符号

const isInteger(target) => (~~target) === target;
const isInteger(target) => (target | 0) === target;
const isInteger(target) => (target & -1) === target;

JavaScript在按位运算时,会将小数部分抛弃,只对整数部分操作。

5 利用Number.isInterger方法

ES6提供的方法

const isInteger(target) => Number.isInteger(target);

直接取整的方法

取整最常用的方法是parseInt,但是这个方法处理科学计数法表示的小数时是错误的:

parseInt(0.01); // 0
parseInt(1e-6); // 1
parseInt(0.0000001); // 1,相当于

可以使用按位运算来取整,可以使用双取反、有符号右移0位,与0按位或,与-1按位与,与0按位异或

注意,这只适用于32位有符号数字所能表示的最小和最大整数之间的数字,即[-2147483648,2147483647]

const getInteger = num => ~~num;
const getInteger = num => num >> 0;
const getInteger = num => num | 0;
const getInteger = num => num ^ 0;
const getInteger = num => num & -1;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值