运算符~"数字"取整

112 阅读2分钟

对下面的数字进行取整,有如下方案:

let num1 = 10.159756;
let num2 = -5.945;

1. parseInt

console.log(parseInt(num1)); // 10
console.log(parseInt(num2)); // -5

2. toFixed()

console.log(num1.toFixed(0), typeof num1.toFixed(0)); // 10 'string'
console.log(num2.toFixed(0), typeof num2.toFixed(0)); // -6 'string'

Tips: toFixed(0) 对负数有点特别,且只对Number类型的数据有效,且转化成String类型的数据

3. Math类

console.log(
  Math.trunc(num1),
  Math.trunc(num1 + ""),
  typeof Math.trunc(num1),
  typeof Math.trunc(num1 + "")
); // 10 10 'number' 'number'
console.log(Math.trunc(num2), Math.trunc(num2 + "")); // -5 -5

** Math.ceil()、Math.floor()、Math.round() 不做赘述**

Tips: truncate:截断。Math类型的方法,对String类型的数字和Number类型的数字都可以转化,返回Number类型的数字

4. 按位类

值得说明的是:位运算只对整数起作用,如果一个运算子不是整数,会自动转为整数后再运行,所以可以实现小数取整。虽然在 JavaScript 内部,数值都是以64位浮点数的形式储存,但是做位运算的时候,是以32位带符号的整数进行运算的,并且返回值也是一个32位带符号的整数。

- 按位或: |
console.log(num1 | 0); // 10
console.log(num2 | 0); // -5

//有没有想过为什么可以取整呢?
// 十进制 => 二进制
let num1 = 10;
console.log(num1.toString(2)); // 1010
// 二进制 => 十进制
let num2 = 1010;
console.log(parseInt(num2, 2)); // 10

// 整数类 => 二进制
console.log(14 | 9); // 15 ,因为:9 => 1001、14 => 1110、15 => 1111
// 小数类 => 二进制
console.log((0.1875).toString(2)); // 0.0011,因为:0.1875 * 2* 2* 2* 2 => 排开整数位,小数位乘以2得到1即停止

Tips: 按位或,有一个位是1的情况下就返回1,而只有在两个位数都是0的情况下才返回0.一个整数与0按位或运算可以得到它本身,一个小数与0按位或者运算可以得到取整的效果

- 按位异或: ^
console.log(num1 ^ 0); // 10
console.log(num2 ^ 0); // -5

Tips: 按位异或 ,两个数值相同时返回0,不同时返回1。一个整数与0按位异或可以保持自身,一个小数与0按位异或可以取整。

- 双按位非: ~~
console.log(~~num1); // 10
console.log(~~num2); // -5
~~ 12.9 // 12
~~'12.9' // 12
typeof ~~12.9 //'number'
typeof ~~'12.9' //'number'

// 模拟掷骰子
const throwdice = () => ~~(Math.random() * 6) + 1; 
throwdice()

Tips: ~~将字符串数字或者数字转换为整型, 按位非运算(不是双按位非)时,任何数字 x 的运算结果都是 -(x + 1)。例如,〜-5 运算结果为 4。

5. 左移和右移

console.log(num1 << 0); // 10
console.log(num2 << 0); // -5
console.log(num1 >> 0); // 10
console.log(num2 >> 0); // -5

Tips: 左移或者右移0位,相当于将该数值转为32位整数,等同于取整,对于正数和负数都有效。