JavaScript 中 x|0 如何对数字进行取整?
在我之前的问题的接受答案中 ( 最快的生成方式是什么javascript 中的随机整数? ),我想知道数字如何通过符号 |
丢失小数位 。
例如:
var x = 5.12042;
x = x|0;
如何将数字降至 5
?
更多示例:
console.log( 104.249834 | 0 ); //104
console.log( 9.999999 | 0 ); // 9
In the accepted answer on my earlier question
( What is the fastest way to generate a random integer in javascript? ), I was wondering how a number loses its decimals via the symbol |
.
For example:
var x = 5.12042;
x = x|0;
How does that floor the number to 5
?
Some more examples:
console.log( 104.249834 | 0 ); //104
console.log( 9.999999 | 0 ); // 9
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为,根据 ECMAScript 规范,按位运算符对每个要计算的表达式调用
ToInt32
。请参阅11.10 二元按位运算符:
Because, according to the ECMAScript specifications, bitwise operators call
ToInt32
on each expression to be evaluated.See 11.10 Binary Bitwise Operators:
位运算符将其参数转换为整数(请参阅 http://es5.github.com/#x9.5< /a>)。
我知道的大多数语言都不支持这种类型的转换:
Bitwise operators convert their arguments to integers (see http://es5.github.com/#x9.5).
Most languages I know don't support this type of conversion:
在执行向下取整时,虽然可以将参数转换为整数,但这不是大多数语言会执行的操作,因为原始类型是浮点数。
在保留数据类型的同时,更好的方法是将指数数字放入尾数并将剩余位归零。
如果您有兴趣,可以查看浮点数的 IEEE 规范。
When doing a
floor
, although it would be possible to convert the argument to an integer, this is not what most languages would do because the original type is a floating-point number.A better way to do it while preserving the data type is to go to
exponent
digits into themantissa
and zero the remaining bits.If you're interested you can take a look at the IEEE spec for floating point numbers.