Number to text
32-bit in partThe text a number is written as, by type.
f32: text = shortest s with fround(+s) = fround(x)
The double branch uses String(x), which is the shortest text that round-trips the 64-bit value. The float branch calls Math.fround first, so a 64-bit value is rounded to 32-bit before it is written; the half branch rounds to 16-bit. -0 is kept as -0 and NaN and the infinities as nan and inf.
/** Shortest text that reads back to the same value at its precision. */
export function num(x, k = 'f64') {
if (Number.isNaN(x)) return 'nan';
if (x === Infinity) return 'inf';
if (x === -Infinity) return '-inf';
if (Object.is(x, -0)) return '-0';
if (k === 'f32') {
const f = Math.fround(x);
for (let p = 1; p <= 9; p++) { const s = shortNum(f, p); if (Math.fround(+s) === f) return s; }
return String(f);
}
if (k === 'f16') {
const h = floatToHalf(x);
for (let p = 1; p <= 6; p++) { const s = shortNum(halfToFloat(h), p); if (floatToHalf(+s) === h) return s; }
return String(halfToFloat(h));
}
return String(x).replace('e+', 'e');
}