JavaScript Math.fround()

The Math.fround() method returns the nearest 32-bit single precision float representation of a number.

Example

// calculate the nearest 32-bit single // precision float representation of 5.05 var num = Math.fround(5.05);
console.log(num); // Output: 5.050000190734863

fround() Syntax

The syntax of the fround() method is:

Math.fround(doubleFloat)

Here, fround() is a static method. Hence, we need to access the method using the class name, Math.


fround() Parameters

The fround() method takes in:

  • doubleFloat - a number.

fround() Return Value

The fround() method returns:

  • the nearest 32-bit single precision float representation of the given number.
  • NaN for non-numeric arguments.

Example 1: JavaScript Math.fround()

// find the nearest 32-bit single precision float representation of 1.5 var num1 = Math.fround(1.5);
console.log(num1);
// find the nearest 32-bit single precision float representation of 1.337 var num2 = Math.fround(1.337);
console.log(num2);

Output

1.5
1.3370000123977661

In the above example,

  • Math.fround(1.5) computes the nearest 32-bit single precision float representation of 1.5
  • Math.fround(1.337) computes the nearest 32-bit single precision float representation of 1.337

Note: JavaScript uses 64-bit double floating-point numbers internally.

In the example above, we can see that the numbers that can be represented perfectly in the binary numeral system (like 1.5) have the same 32-bit single precision float representation.

However, some that can't be represented perfectly (like 1.337 or 5.05) differ in 32-bit and 64-bit.


Example 2: fround() With Large Numbers

// find the nearest 32-bit single precision float representation of 2 ** 130 var num = Math.fround(2 ** 130);
console.log(num); // Output: Infinity

In the above example, we have used Math.fround() to compute the nearest 32-bit single precision float representation for an extremely large number: 2 ** 130 which is 1.361129467683754e+39.

The output indicates that the result is Infinity for extremely large numbers.


Also Read:

Did you find this article helpful?