Math.fround()

Math.fround(x)
Returns: number · Updated March 16, 2026 · Math
math floating-point precision

The Math.fround() function returns the nearest 32-bit single precision float representation of a number. This is particularly useful when working with WebGL or other APIs that require 32-bit float precision, ensuring consistent behavior across JavaScript number operations and hardware-level float computations.

Syntax

Math.fround(x)

Examples

Basic usage

console.log(Math.fround(1));
// 1

console.log(Math.fround(1.5));
// 1.5

console.log(Math.fround(1.23456789));
// 1.2345679

Precision loss demonstration

const original = 0.1 + 0.2;
console.log(original);
// 0.30000000000000004

console.log(Math.fround(original));
// 0.30000001192092896

// The fround result is the actual 32-bit float representation
const frounded = Math.fround(0.1 + 0.2);
console.log(frounded === 0.30000001192092896);
// true

Comparing with full precision

const value = Math.PI;
console.log(value);
// 3.141592653589793

console.log(Math.fround(value));
// 3.1415927

// The difference
console.log(value - Math.fround(value));
// 6.98491930961609e-10

Large numbers

console.log(Math.fround(1e10));
// 10000000000

console.log(Math.fround(1.7976931348623157e+308));
// Infinity (exceeds 32-bit float range)

// Near the precision limit
console.log(Math.fround(16777216));
// 16777216

console.log(Math.fround(16777217));
// 16777216 (loses precision at this scale)

Common Patterns

WebGL compatibility

function setGLMatrixElement(gl, location, value) {
  // Ensure 32-bit float precision for WebGL
  const floatValue = Math.fround(value);
  gl.uniform1f(location, floatValue);
}

// Without fround, you might get unexpected results
const shaderValue = Math.sin(Math.PI);
console.log(Math.fround(shaderValue));
// 0

Consistent floating-point comparisons

function floatsEqual(a, b, tolerance) {
  return Math.abs(Math.fround(a) - Math.fround(b)) < tolerance;
}

console.log(floatsEqual(0.1 + 0.2, 0.3, 0.0001));
// true

Audio processing

class AudioProcessor {
  constructor() {
    this.gain = 0;
  }
  
  setGain(value) {
    // Audio APIs often use 32-bit floats
    this.gain = Math.fround(Math.max(0, Math.min(1, value)));
  }
}

const processor = new AudioProcessor();
processor.setGain(0.755);
console.log(processor.gain);
// 0.7550000252723694

See Also

  • math::clz32 — count leading zeros in 32-bit representation
  • number::to-fixed — format numbers with fixed decimal places
  • math::trunc — truncate to integer by removing fractional digits