JavaScript Math.fround() Method



The JavaScript Math.fround() method is used to return the nearest 32-bit single precision float representation of the provided number. It takes a single argument, "x", which is the number that we want to convert to its nearest single precision float representation. If the provided argument is NaN, this method returns NaN. If (+) Infinity or (-) Infinity is provided as an argument, it returns (+) Infinity and (-) Infinity, respectively.

Syntax

Following is the syntax of JavaScript Math.fround() method −

Math.fround(doubleFloat)

Parameters

This method accepts only one parameter. The same is described below −

  • doubleFloat: The number for which we want to find the nearest single precision float representation.

Return value

This method returns the nearest 32-bit single precision float representation of the provided number.

Example 1

In the following example, we are demonstrating the usage of JavaScript Math.fround() method −

<html>
<body>
<script>
   const num1 = Math.fround(5.80);
   const num2 = Math.fround(5.50);
   const num3 = Math.fround(5.49);

   const num4 = Math.fround(-5.80);
   const num5 = Math.fround(-5.50);
   const num6 = Math.fround(-5.49);
   document.write(num1, "<br>",num2 , "<br>", num3, "<br>", num4, "<br>", num5, "<br>", num6, "<br>");
</script>
</body>
</html>

Output

After executing the above program, this method returns the nearest single precision float representation for the given numbers.

Example 2

If we provide "0" as an argument to this method, it returns 0 as result −

<html>
<body>
<script>
   const num = Math.fround(0);
   document.write(num);
</script>
</body>
</html>

Output

As we can see in the output, 0 has been returned as result.

Example 3

If NaN is provided as an argument, the result will be NaN as well −

<html>
<body>
<script>
   const num = Math.fround(NaN);
   document.write(num);
</script>
</body>
</html>

Output

As we can see in the output, NaN has been returned as result.

Example 4

If "Infinity" is provided as an argument, the result will be Infinity −

<html>
<body>
<script>
   const num = Math.fround(Infinity);
   document.write(num);
</script>
</body>
</html>

Output

As we can see in the output, Infinity has been returned as result.