11export function useNumberFormatter ( options ?: Intl . NumberFormatOptions ) {
2- const { locale } = useI18n ( )
2+ const { userLocale } = useUserLocale ( )
33
4- return computed ( ( ) => new Intl . NumberFormat ( locale . value , options ) )
4+ return computed (
5+ ( ) =>
6+ new Intl . NumberFormat (
7+ userLocale . value ,
8+ options ?? {
9+ maximumFractionDigits : 0 ,
10+ } ,
11+ ) ,
12+ )
513}
614
715export const useCompactNumberFormatter = ( ) =>
@@ -12,26 +20,45 @@ export const useCompactNumberFormatter = () =>
1220 } )
1321
1422export const useBytesFormatter = ( ) => {
15- const { t } = useI18n ( )
16- const decimalNumberFormatter = useNumberFormatter ( {
17- maximumFractionDigits : 1 ,
23+ const { userLocale } = useUserLocale ( )
24+
25+ const units = [ 'byte' , 'kilobyte' , 'megabyte' , 'gigabyte' , 'terabyte' , 'petabyte' ]
26+
27+ // Create formatters reactively based on the user's preferred locale.
28+ // This ensures that when the locale (or the setting) changes, all formatters are recreated.
29+ const formatters = computed ( ( ) => {
30+ const locale = userLocale . value
31+ const map = new Map < string , Intl . NumberFormat > ( )
32+
33+ units . forEach ( unit => {
34+ map . set (
35+ unit ,
36+ new Intl . NumberFormat ( locale , {
37+ style : 'unit' ,
38+ unit,
39+ unitDisplay : 'short' ,
40+ maximumFractionDigits : 2 ,
41+ } ) ,
42+ )
43+ } )
44+
45+ return map
1846 } )
19- const KB = 1000
20- const MB = 1000 * 1000
2147
2248 return {
2349 format : ( bytes : number ) => {
24- if ( bytes < KB )
25- return t ( 'package.size.b' , {
26- size : decimalNumberFormatter . value . format ( bytes ) ,
27- } )
28- if ( bytes < MB )
29- return t ( 'package.size.kb' , {
30- size : decimalNumberFormatter . value . format ( bytes / KB ) ,
31- } )
32- return t ( 'package.size.mb' , {
33- size : decimalNumberFormatter . value . format ( bytes / MB ) ,
34- } )
50+ let value = bytes
51+ let unitIndex = 0
52+
53+ // Use 1_000 as base (SI units) instead of 1_024.
54+ while ( value >= 1_000 && unitIndex < units . length - 1 ) {
55+ value /= 1_000
56+ unitIndex ++
57+ }
58+
59+ const unit = units [ unitIndex ] !
60+ // Accessing formatters.value here establishes the reactive dependency
61+ return formatters . value . get ( unit ) ! . format ( value )
3562 } ,
3663 }
3764}
0 commit comments