Created
January 27, 2025 17:36
-
-
Save markusand/d7f355c970710b710bce9559c0583d40 to your computer and use it in GitHub Desktop.
[Vue] Format numbers depending on locale
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
export type Unit = 'acre' | 'bit' | 'byte' | 'celsius' | 'centimeter' | 'day' | 'degree' | 'fahrenheit' | 'fluid-ounce' | 'foot' | 'gallon' | 'gigabit' | 'gigabyte' | 'gram' | 'hectare' | 'hour' | 'inch' | 'kilobit' | 'kilobyte' | 'kilogram' | 'kilometer' | 'liter' | 'megabit' | 'megabyte' | 'meter' | 'microsecond' | 'mile' | 'mile-scandinavian' | 'milliliter' | 'millimeter' | 'millisecond' | 'minute' | 'month' | 'nanosecond' | 'ounce' | 'percent' | 'petabyte' | 'pound' | 'second' | 'stone' | 'terabit' | 'terabyte' | 'week' | 'yard' | 'year'; | |
export type FormatOptions = { | |
currency?: string; | |
units?: 'short' | 'narrow' | 'long'; | |
sign?: boolean; | |
integers?: number; | |
decimals?: number; | |
round?: 'ceil' | 'floor' | 'expand' | 'trunc'; | |
notation?: 'standard' | 'scientific' | 'engineering' | 'compact'; | |
}; | |
export const useFormat = (options?: FormatOptions) => { | |
const { locale } = useI18n(); | |
const { currency = 'EUR', units = 'long', notation, round, sign, decimals, integers } = options || {}; | |
const config = { | |
signDisplay: sign ? 'exceptZero' : 'auto', | |
minimumIntegerDigits: integers, | |
minimumFractionDigits: decimals, | |
maximumFractionDigits: decimals, | |
roundingMode: round, | |
notation, | |
}; | |
return computed(() => { | |
const NUMBER = new Intl.NumberFormat(locale.value, config).format; | |
const PRICE = new Intl.NumberFormat(locale.value, { style: 'currency', currency, ...config }).format; | |
const PERCENT = new Intl.NumberFormat(locale.value, { style: 'percent', ...config }).format; | |
const UNIT = (number: number, unit: Unit) => { | |
const formatter = new Intl.NumberFormat(locale.value, { style: 'unit', unit, unitDisplay: units, ...config }); | |
return formatter.format(number); | |
}; | |
return { NUMBER, PRICE, PERCENT, UNIT }; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment