2025-08-14 21:48:38 +01:00
|
|
|
const formatters = new WeakMap<object, Intl.NumberFormat>()
|
2023-06-11 19:08:16 +01:00
|
|
|
|
2025-06-30 23:08:05 +01:00
|
|
|
export function useCompactNumber(truncate = false, fractionDigits = 2, locale?: string) {
|
2025-08-14 21:48:38 +01:00
|
|
|
const context = {}
|
2023-06-11 19:08:16 +01:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
let formatter = formatters.get(context)
|
2023-06-11 19:08:16 +01:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
if (!formatter) {
|
|
|
|
|
formatter = new Intl.NumberFormat(locale, {
|
|
|
|
|
notation: 'compact',
|
|
|
|
|
maximumFractionDigits: fractionDigits,
|
|
|
|
|
})
|
|
|
|
|
formatters.set(context, formatter)
|
|
|
|
|
}
|
2023-06-11 19:08:16 +01:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
function format(value: number): string {
|
|
|
|
|
let formattedValue = value
|
|
|
|
|
if (truncate) {
|
|
|
|
|
const scale = Math.pow(10, fractionDigits)
|
|
|
|
|
formattedValue = Math.floor(value * scale) / scale
|
|
|
|
|
}
|
|
|
|
|
return formatter!.format(formattedValue)
|
|
|
|
|
}
|
2023-06-11 19:08:16 +01:00
|
|
|
|
2025-08-14 21:48:38 +01:00
|
|
|
return format
|
2023-06-11 19:08:16 +01:00
|
|
|
}
|