Math.fround()
function.The
Math.fround()
function returns the nearest float representation of a number.
But when it is passed the float number Math.fround(1.5)
it returns the same(1.5) value.
But when it is passed the float number Math.fround(1.55)
it returns a different value 1.5499999523162841
. why and How?
- 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
.
To understand how this function works you actually have to know the following topics:
The ECMA script specifies the following algorithm for the conversion:
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.
So, let's do that for 1.5
and 1.55
.
1) Represent in 64bit float
0 01111111111 1000000000000000000000000000000000000000000000000000
2) Represent in the scientific notation
1.1000000000000000000000000000000000000000000000000000 x 2^0
3) Round to 23 bit mantissa
1.10000000000000000000000
4) Convert to decimal:
1.5
1) Represent in 64bit float
0 01111111111 1000110011001100110011001100110011001100110011001101
2) Represent in the scientific notation
1.1000110011001100110011001100110011001100110011001101 x 2^0
3) Round to 23 bit mantissa
1.10001100110011001100110
4) Convert to decimal:
1.5499999523162841
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With