fround Rounds Doubles To float32

Math.fround rounds a double to the nearest float32 value kept as a double: 1.1 drifts, 1.5 survives, integers past 2^24 and huge magnitudes clamp.

JavascriptData Integrity

Code

javascriptsnippet
13 lines
// Math.fround rounds a double to the nearest float32 value, kept as a double
console.log('1.1 ->', Math.fround(1.1));
console.log('exact round trip:', Math.fround(1.1) === 1.1);

// Values representable in float32 survive unchanged
console.log('1.5 ->', Math.fround(1.5), Math.fround(1.5) === 1.5);

// float32 has a 24-bit mantissa, so integers past 2^24 round down
console.log('16777217 ->', Math.fround(16777217)); // 2^24 + 1
console.log('16777216 ->', Math.fround(16777216)); // 2^24 itself is exact

// Doubles beyond the float32 range overflow to Infinity
console.log('huge ->', Math.fround(3.5e38));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

1.1 -> 1.100000023841858
exact round trip: false
1.5 -> 1.5 true
16777217 -> 16777216
16777216 -> 16777216
huge -> Infinity

Applying it

The demo output is labeled (1.1 ->, exact round trip:, 1.5 ->), so every printed line maps back to its originating operation.

Output is labeled for readability — expect lines prefixed with 1.1 ->, exact round trip:, 1.5 ->.

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API.