Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain: Math.fround() function

How do works 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.
like image 724
Ramesh Rajendran Avatar asked Jan 31 '23 02:01

Ramesh Rajendran


1 Answers

To understand how this function works you actually have to know the following topics:

  • 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

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.

Math.fround(1.5)

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

Math.fround(1.55)

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
like image 198
Max Koretskyi Avatar answered Feb 02 '23 18:02

Max Koretskyi