JavaScript Math.fround() Method
-
Syntax of JavaScript
Math.fround()
Method -
Example Codes: Use the
Math.fround()
Method -
Example Codes: Use the
Math.fround()
Method With Positive and Negative Numbers -
Example Codes: Use the
Math.fround()
Method With Exception
By default, JavaScript uses the 64-bit floating numbers while performing operations on numbers. But sometimes, we may need to work with the 32-bit floating numbers.
It may fail while checking the equality of 32-bit numbers with 64-bit numbers. To deal with this situation, JavaScript provides an inbuilt function named Math.fround()
.
This function is used to cast 64-bit numbers to 32-bit and find a single precision float of the given number in the nearest 32-bit.
Syntax of JavaScript Math.fround()
Method
Math.fround(data)
Parameters
data (required) |
data refers to a number. |
Return
A single precision float of the given number in the nearest 32-bit is returned. This function will return NaN
if the given number is non-numeric.
Example Codes: Use the Math.fround()
Method
const result1 = Math.fround(2.5)
const result2 = Math.fround(2.2)
console.log(result1)
console.log(result1 === 2.5)
console.log(result2)
console.log(result2 === 2.2)
Output:
2.5
true
2.200000047683716
false
First, we used this function with the number 2.5
, which can be represented in the binary numeral system and is identical in 32-bit and 64-bit. As a result, it returns true
when we have compared it.
Second, we used this function again with the number 2.2
, which cannot be represented in the binary numeral system exactly and is different in 32-bit and 64-bit. As a result, it returns false
when we have compared it.
Example Codes: Use the Math.fround()
Method With Positive and Negative Numbers
const result1 = Math.fround(2.342)
const result2 = Math.fround(-2.342)
console.log(result1)
console.log(result2)
Output:
2.3420000076293945
-2.3420000076293945
The Math.fround()
function can handle positive and negative numbers. To check this, we have passed the same number as the parameter of this function, but one is positive, and the other is negative.
Example Codes: Use the Math.fround()
Method With Exception
const result1 = Math.fround(2.32 ** 200)
const result2 = Math.fround()
console.log(result1)
console.log(result2)
Output:
Infinity
NaN
First, we passed the number 2.32 ** 200
as the parameter of the Math.fround()
function. This number is too big to handle for 32-bit; as a result, it returned Infinity
.
Second, we did not pass anything as the parameter; it simply returns NaN
.
Niaz is a professional full-stack developer as well as a thinker, problem-solver, and writer. He loves to share his experience with his writings.
LinkedIn