-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: adapts the formatter to not round but rather truncate to one de…
…cimal digit
- Loading branch information
1 parent
b9a4383
commit c2d18d2
Showing
3 changed files
with
42 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,36 @@ | ||
/** | ||
* Formats the given number in thousands order of magnitude and truncates the decimal part to 1 digit. | ||
* | ||
* @param {number} value - The number to be formatted. | ||
* @returns {string} The formatted string representation of the number. | ||
*/ | ||
export function formatValue(value: number): string { | ||
const numberFormat = new Intl.NumberFormat(undefined, { | ||
notation: 'compact', | ||
maximumFractionDigits: 2, | ||
}) | ||
|
||
return `${numberFormat.format(value)}` | ||
const parts = numberFormat.formatToParts(value) | ||
let integer = '0' | ||
let decimalPart = '' | ||
let compact = '' | ||
|
||
for (const part of parts) { | ||
if (part.type === 'integer') { | ||
integer = part.value | ||
} else if (part.type === 'decimal') { | ||
if (integer.length === 1) { | ||
decimalPart = part.value | ||
} | ||
} else if (part.type === 'fraction') { | ||
if (integer.length === 1) { | ||
// Truncates the fraction part to 1 decimal place if the value has a single integer digit | ||
decimalPart = `${decimalPart}${part.value[0]}` | ||
} | ||
} else if (part.type === 'compact') { | ||
compact = part.value | ||
} | ||
} | ||
|
||
return `${integer}${decimalPart}${compact}` | ||
} |