JSFiddle - React, Tailwind, and code Playground

by xonev

TypeScript

/**
   * Returns a string representation of a number with x or fewer significant digits
   *
   * @param {number|string} num - the number to be processed
   * @param {number} length - the number of significant digits
   * @return {string} String representation of the number with length x or less
   */
  function roundFloatToSignificantDigits(num, length) {

    let processedLabel;
    // To be consistent with the "auto" format, these values are set so that large and small numbers transition to
    // e-notation at similar thresholds (i.e when abs(value) > MAX_EXP_THRESHOLD and when abs(value) < MIN_EXP_THRESHOLD
    const MIN_EXP_THRESHOLD = 1e-5;
    const MAX_EXP_THRESHOLD = 1e6;

    const valueStr = (+num).toPrecision(length);
    const value = +valueStr;

    if ((Math.abs(value) >= MAX_EXP_THRESHOLD || Math.abs(value) < MIN_EXP_THRESHOLD) && value !== 0) {
      processedLabel = value.toExponential(length - 1);
    } else if (valueStr.includes('e') && Math.abs(value) > MIN_EXP_THRESHOLD) {
      processedLabel = value.toString();
    } else {
      processedLabel = valueStr;
    }

    return processedLabel;
  }
  
  console.log('test');