2022-12-02 02:18:36 +00:00
|
|
|
import type { MaybeRef } from '@vueuse/shared'
|
|
|
|
|
2022-11-25 21:57:40 +00:00
|
|
|
const formatter = Intl.NumberFormat()
|
|
|
|
|
2022-12-02 02:18:36 +00:00
|
|
|
export const humanReadableNumber = (
|
|
|
|
num: number,
|
|
|
|
{ k, m }: { k: string; m: string } = { k: 'K', m: 'M' },
|
|
|
|
useFormatter: Intl.NumberFormat = formatter,
|
|
|
|
) => {
|
2022-11-25 21:57:40 +00:00
|
|
|
if (num < 10000)
|
2022-12-02 02:18:36 +00:00
|
|
|
return useFormatter.format(num)
|
2022-11-25 21:57:40 +00:00
|
|
|
|
|
|
|
if (num < 1000000)
|
2022-12-02 02:18:36 +00:00
|
|
|
return `${Math.floor(num / 1000)}${k}`
|
|
|
|
|
|
|
|
return `${Math.floor(num / 1000000)}${m}`
|
|
|
|
}
|
2022-11-25 21:57:40 +00:00
|
|
|
|
2022-12-02 02:18:36 +00:00
|
|
|
export const formattedNumber = (num: number, useFormatter: Intl.NumberFormat = formatter) => {
|
|
|
|
return useFormatter.format(num)
|
2022-11-25 21:57:40 +00:00
|
|
|
}
|
|
|
|
|
2022-12-02 02:18:36 +00:00
|
|
|
export const useHumanReadableNumber = () => {
|
|
|
|
const i18n = useI18n()
|
|
|
|
const numberFormatter = $computed(() => Intl.NumberFormat(i18n.locale.value))
|
|
|
|
return {
|
|
|
|
formatHumanReadableNumber: (num: MaybeRef<number>) => {
|
|
|
|
return humanReadableNumber(
|
|
|
|
unref(num),
|
|
|
|
{ k: i18n.t('common.kiloSuffix'), m: i18n.t('common.megaSuffix') },
|
|
|
|
numberFormatter,
|
|
|
|
)
|
|
|
|
},
|
|
|
|
formatNumber: (num: MaybeRef<number>) => {
|
|
|
|
return formattedNumber(
|
|
|
|
unref(num),
|
|
|
|
numberFormatter,
|
|
|
|
)
|
|
|
|
},
|
|
|
|
forSR: (num: MaybeRef<number>) => {
|
|
|
|
return unref(num) > 10000
|
|
|
|
},
|
|
|
|
}
|
2022-11-25 21:57:40 +00:00
|
|
|
}
|