Math.fround()
函数是如何工作的。
The
Math.fround()
function returns the nearest float representation of a number.
但是当它传递 float Math.fround(1.5)
时,它返回相同的 (1.5) 值。
但是当它传递 float Math.fround(1.55)
时,它返回一个不同的值 1.5499999523162841
。 为什么以及如何?
- I am confused about how
Math.fround()
works.- How is it different from the
Math.round()
function?- Also let me know why it's not supported in
Internet Explorer
.
最佳答案
要了解此功能的工作原理,您实际上必须了解以下主题:
- JavaScript’s Number type in details
- The simple math behind decimal-binary conversion algorithms
- How to round binary numbers
- The mechanics behind exponent bias in floating point
ECMA 脚本指定 the following algorithm对于转换:
When Math.fround is called with argument x, the following steps are taken:
- If x is NaN, return NaN.
- If x is one of +0, -0, +∞, -∞, return x.
- Let x32 be the result of converting x to a value in IEEE 754-2008 binary32 format using roundTiesToEven.
- Let x64 be the result of converting x32 to a value in IEEE 754-2008 binary64 format.
- Return the ECMAScript Number value corresponding to x64.
那么,让我们为 1.5
和 1.55
这样做。
数学.fround(1.5)
1)以64位 float 表示
0 01111111111 1000000000000000000000000000000000000000000000000000
2)用科学记数法表示
1.1000000000000000000000000000000000000000000000000000 x 2^0
3) 四舍五入到23位尾数
1.10000000000000000000000
4) 转换为十进制:
1.5
Math.fround(1.55)
1)以64位 float 表示
0 01111111111 1000110011001100110011001100110011001100110011001101
2)用科学记数法表示
1.1000110011001100110011001100110011001100110011001101 x 2^0
3) 四舍五入到23位尾数
1.10001100110011001100110
4) 转换为十进制:
1.5499999523162841
关于javascript - 解释: Math. fround()函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44817932/