All files / math round-to-significant-digits.ts

100% Statements 1/1
100% Branches 3/3
100% Functions 1/1
100% Lines 1/1

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14                      9x    
/**
 * 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;
}