diff --git a/app/ts/components/AbbreviatedValue.tsx b/app/ts/components/AbbreviatedValue.tsx index 6ddcf0a3..bf7890a9 100644 --- a/app/ts/components/AbbreviatedValue.tsx +++ b/app/ts/components/AbbreviatedValue.tsx @@ -1,16 +1,28 @@ -import { parseNumericTerm } from '../library/utilities.js' - export const AbbreviatedValue = ({ floatValue }: { floatValue: number }) => { - const { coefficient, exponent } = parseNumericTerm(floatValue) + const prefixes = [ + { value: 1e9, symbol: 'G' }, + { value: 1e6, symbol: 'M' }, + { value: 1e3, symbol: 'k' }, + ]; + + for (const prefix of prefixes) { + if (floatValue >= prefix.value) { + return <>{toFixedLengthDigits(floatValue / prefix.value) + prefix.symbol} + } + } - if (exponent < 0) { - const leadingZeros = Math.abs(exponent) - 1 - return <>0.{'0'.repeat(leadingZeros)}{coefficient} + // if value is a fraction of 1 + if (floatValue && floatValue % 1 === floatValue) { + const [coefficient, exponent] = floatValue.toExponential().split('e') + const leadingZerosCount = Math.abs(parseInt(exponent)) - 1 + const significantDigits = coefficient.replace('.', '') + return <>0.{'0'.repeat(leadingZerosCount)}{significantDigits} } - const prefixes = ['', 'k', 'M', 'G'] - const prefix = prefixes[Math.floor(exponent/3)] - const displayValue = coefficient.toFixed(3) + return <>{toFixedLengthDigits(floatValue)} +} - return <>{displayValue}{prefix} +function toFixedLengthDigits(num: number, max: number = 5) { + const formatter = new Intl.NumberFormat('en-US', { maximumSignificantDigits: max, useGrouping: false }) + return formatter.format(num) } diff --git a/app/ts/library/utilities.ts b/app/ts/library/utilities.ts index 0d7f8542..1ec2419b 100644 --- a/app/ts/library/utilities.ts +++ b/app/ts/library/utilities.ts @@ -64,9 +64,3 @@ export function areEqualStrings(a: string, b: string, caseSensitive?: true) { if (caseSensitive) return a === b return a.toLowerCase() === b.toLowerCase() } - -export function parseNumericTerm(num: number): { coefficient: number, exponent: number } { - const [c, e] = num.toExponential().split('e') - const exponent = parseInt(e) - return { coefficient: parseFloat(c), exponent } -}