All files / packages/core/src/utilities roundNumber.ts

66.66% Statements 8/12
59.09% Branches 13/22
33.33% Functions 1/3
72.72% Lines 8/11

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 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                                    146x     146x     146x 146x 146x 17x     129x                         129x                            
import { EPSILON } from '../constants';
 
/**
 * Truncates decimal points to that there is at least 1+precision significant
 * digits.
 *
 * For example, with the default precision 2 (3 significant digits)
 * * Values larger than 100 show no information after the decimal point
 * * Values between 10 and 99 show 1 decimal point
 * * Values between 1 and 9 show 2 decimal points
 *
 * @param value - to return a fixed measurement value from
 * @param precision - defining how many digits after 1..9 are desired
 */
function roundNumber(
  value: string | number | (string | number)[],
  precision = 2
): string {
  Iif (Array.isArray(value)) {
    return value.map((v) => roundNumber(v, precision)).join(', ');
  }
  Iif (value === undefined || value === null || value === '') {
    return 'NaN';
  }
  value = Number(value);
  const absValue = Math.abs(value);
  if (absValue < 0.0001) {
    return `${value}`;
  }
  const fixedPrecision =
    absValue >= 100
      ? precision - 2
      : absValue >= 10
      ? precision - 1
      : absValue >= 1
      ? precision
      : absValue >= 0.1
      ? precision + 1
      : absValue >= 0.01
      ? precision + 2
      : absValue >= 0.001
      ? precision + 3
      : precision + 4;
  return value.toFixed(fixedPrecision);
}
 
/**
 * Rounds a number to the nearest multiple of EPSILON.
 * @param value - The number to round.
 * @returns The rounded number.
 */
function roundToPrecision(value) {
  return Math.round(value / EPSILON) * EPSILON;
}
 
export { roundToPrecision };
export default roundNumber;