快速浮点数转整数
浮点数转整数常用的有以下几种方法,parseInt() Math.floor() Math.ceil() Math.round()
在此,还有一种更快的方法可以使用|(位或运算符)将浮点数截断为整数。
console.log(23.9 | 0); // Result: 23 console.log(-23.9 | 0); // Result: -23
console.log(1553 / 10 | 0) // Result: 155 console.log(1553 / 100 | 0) // Result: 15 console.log(1553 / 1000 | 0) // Result: 1
|的行为取决于处理的是正数还是负数,所以最好只在确定的情况下使用这个快捷方式。
如果n为正,则n | 0有效地向下舍入。 如果n为负数,则有效地向上舍入。 更准确地说,此操作将删除小数点后面的任何内容,将浮点数截断为整数。
浙公网安备 33010602011771号