JavaScript Reference ยท Math
Math.fround() and Math.clz32()
Reference for Math.fround() and Math.clz32(): rounding to 32-bit floats, counting leading zero bits, bit lengths and when these low-level helpers matter.
Two small methods of Math deal with the way numbers are stored in memory. Math.fround(x) rounds a number to the nearest 32-bit floating-point value and returns it as an ordinary JavaScript number, so you can see what you would get in a single-precision float. Math.clz32(x) counts the leading zero bits in the 32-bit unsigned integer form of x.
You will rarely need either in everyday code. They matter when you work with typed arrays, graphics and audio buffers, binary formats, or when you need to mirror the behavior of other languages' float type.
Math.fround(x) Math.clz32(x)
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Math.fround(x) Math.clz32(x)
| Name | Description |
|---|---|
x |
A number (or a value that converts to one). |
Return value: fround() returns the nearest 32-bit float, as a regular double. The result is NaN for NaN, and Infinity when x is too big for a 32-bit float. clz32() returns an integer from 0 to 32: the number of leading zero bits after x is converted to an unsigned 32-bit integer.
Exceptions: a BigInt argument throws a TypeError.
Usage notes
fround()loses precision on purpose. The returned value is still stored as a 64-bit double, but it now holds only a 32-bit float's value, with about seven decimal digits of accuracy.- Typed arrays.
Float32Arrayapplies the same rounding when you assign to it, soMath.fround()lets plain code match those results. - Compare precisely.
Math.fround(0.1) === 0.1isfalse. When comparing against 32-bit data,froundboth sides. - Integers above 2^24 (16,777,216) can no longer all be stored in a 32-bit float.
clz32()converts first, the way bitwise operators do: fractions are truncated, values wrap modulo 2^32, andNaNorInfinitybecome0. SoMath.clz32(0),Math.clz32(NaN)andMath.clz32(Infinity)are all32.- Bit length and logarithms.
32 - Math.clz32(n)is the bit length of an unsigned integer, and31 - Math.clz32(n)isfloor(log2(n))forn > 0, without floating-point error. - Related helper:
Math.imul()multiplies two numbers as 32-bit integers, with wraparound.
Browser support
Both methods are part of ES2015 and supported in all current browsers.