-
-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy pathuseNumberFormatter.ts
More file actions
64 lines (54 loc) · 1.57 KB
/
useNumberFormatter.ts
File metadata and controls
64 lines (54 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
export function useNumberFormatter(options?: Intl.NumberFormatOptions) {
const { userLocale } = useUserLocale()
return computed(
() =>
new Intl.NumberFormat(
userLocale.value,
options ?? {
maximumFractionDigits: 0,
},
),
)
}
export const useCompactNumberFormatter = () =>
useNumberFormatter({
notation: 'compact',
compactDisplay: 'short',
maximumFractionDigits: 1,
})
export const useBytesFormatter = () => {
const { userLocale } = useUserLocale()
const units = ['byte', 'kilobyte', 'megabyte', 'gigabyte', 'terabyte', 'petabyte']
// Create formatters reactively based on the user's preferred locale.
// This ensures that when the locale (or the setting) changes, all formatters are recreated.
const formatters = computed(() => {
const locale = userLocale.value
const map = new Map<string, Intl.NumberFormat>()
units.forEach(unit => {
map.set(
unit,
new Intl.NumberFormat(locale, {
style: 'unit',
unit,
unitDisplay: 'short',
maximumFractionDigits: 2,
}),
)
})
return map
})
return {
format: (bytes: number) => {
let value = bytes
let unitIndex = 0
// Use 1_000 as base (SI units) instead of 1_024.
while (value >= 1_000 && unitIndex < units.length - 1) {
value /= 1_000
unitIndex++
}
const unit = units[unitIndex]!
// Accessing formatters.value here establishes the reactive dependency
return formatters.value.get(unit)!.format(value)
},
}
}