Skip to content

roundToSignificantDigits function ​

Rounds a number to a number of significant digits, whatever its magnitude.

ts
import { roundToSignificantDigits } from 'utils';

Signature ​

ts
export function roundToSignificantDigits(value: number, digits = 3): number

Parameters ​

NameDescription
valueThe number to round.
digitsThe significant digits to keep, from 1 to 100. Defaults to 3.

Returns ​

The rounded number; NaN and infinities unchanged.

Example ​

ts
roundToSignificantDigits(123_456); // 123000
roundToSignificantDigits(0.001_234_5); // 0.00123

Tests ​

Line coverage: 100 %.

  • ✅ rounds 123456 to 3 digits: 123000
  • ✅ rounds 0.0012345 to 3 digits: 0.00123
  • ✅ rounds -9.876 to 2 digits: -9.9
  • ✅ rounds 0.30000000000000004 to 15 digits: 0.3
  • ✅ rounds 0 to 3 digits: 0
  • ✅ rounds Infinity to 3 digits: Infinity
  • ✅ keeps NaN
  • ✅ takes the defaults

Source ​

src/math/round-to-significant-digits.ts (on GitHub)

Source code
ts
/**
 * Rounds a number to a number of significant digits, whatever its magnitude.
 *
 * @param value - The number to round.
 * @param digits - The significant digits to keep, from 1 to 100. Defaults to `3`.
 * @returns The rounded number; `NaN` and infinities unchanged.
 * @example
 * roundToSignificantDigits(123_456); // 123000
 * roundToSignificantDigits(0.001_234_5); // 0.00123
 */
export function roundToSignificantDigits(value: number, digits = 3): number {
  return Number.isFinite(value) ? Number(value.toPrecision(digits)) : value;
}
Test file
ts
import { roundToSignificantDigits } from './round-to-significant-digits';

describe(roundToSignificantDigits, () => {
  it.for([
    [123_456, 3, 123_000],
    [0.0012345, 3, 0.00123],
    [-9.876, 2, -9.9],
    [0.1 + 0.2, 15, 0.3],
    [0, 3, 0],
    [Infinity, 3, Infinity],
  ] as const)('rounds %s to %s digits: %s', ([value, digits, expected]) => {
    expect(roundToSignificantDigits(value, digits)).toBe(expected);
  });

  it('keeps NaN', () => {
    expect(roundToSignificantDigits(NaN, 2)).toBeNaN();
  });

  it('takes the defaults', () => {
    expect(roundToSignificantDigits(123_456)).toStrictEqual(roundToSignificantDigits(123_456, 3));
  });
});

Keywords: round, to, significant, digits, math, function

Generated from the JSDoc of the sources.