|
| 1 | +export const formatPercentageToFirstNonZeroDigit = ( |
| 2 | + percentage: number, |
| 3 | +): string => { |
| 4 | + if (percentage === 0) return "0"; |
| 5 | + |
| 6 | + if (percentage < 1) { |
| 7 | + const NumberFormat = new Intl.NumberFormat("en-US", { |
| 8 | + style: "decimal", |
| 9 | + notation: "standard", |
| 10 | + maximumSignificantDigits: 21, |
| 11 | + }); |
| 12 | + |
| 13 | + const result = NumberFormat.format(percentage); |
| 14 | + |
| 15 | + // Match the first 2 non-zero digits after the decimal point |
| 16 | + const match = result.match(/\d*\.\d*?[1-9](?:\d*[1-9]|\d)?/); |
| 17 | + |
| 18 | + // If no decimal or no non-zero digits after decimal, return rounded integer |
| 19 | + if (!match) { |
| 20 | + return Math.round(percentage).toString(); |
| 21 | + } |
| 22 | + |
| 23 | + // Check if we found 1 or 2 non-zero digits after the decimal point |
| 24 | + // Skip leading zeros after decimal points |
| 25 | + const numbersAfterDecimal = match[0].split(".")[1]; |
| 26 | + const isSingleNonZeroDigit = |
| 27 | + numbersAfterDecimal.replace(/^0+/, "").length === 1; |
| 28 | + |
| 29 | + // If we have 1 significant digit, return the match |
| 30 | + if (isSingleNonZeroDigit) { |
| 31 | + return match[0]; |
| 32 | + } |
| 33 | + |
| 34 | + // If we have 2 significant digits, get the number of digits after the decimal point |
| 35 | + const fractionDigits = numbersAfterDecimal.length; |
| 36 | + return new Intl.NumberFormat("en-US", { |
| 37 | + style: "decimal", |
| 38 | + notation: "standard", |
| 39 | + // maximumSignificantDigits: decimalDigits - 1, |
| 40 | + maximumFractionDigits: fractionDigits - 1, |
| 41 | + }).format(percentage); |
| 42 | + } |
| 43 | + |
| 44 | + // Round to 1 digit, strip trailing zeros |
| 45 | + return percentage.toFixed(1).replace(/\.?0+$/, ""); |
| 46 | +}; |
0 commit comments