In my application there are several places where the user is expected to enter a monetary value. The application supports storing these monetary values in multiple currencies as well as localization.
I'm using the Intl.NumberFormat object in Javascript to format a number into any currency and locale I need, but there's no way to unformat the number using that.
All of the libraries I've found so far require you to provide the decimal and thousands separators in order for the formatting/unformatting functions to work. However, I need a way to find what the decimal and thousands separators are in the first place so I can't use those.
How can I reliably get the decimal separator for the current locale?
Click Windows/Start and select Control Panel. Select Region and Language and click on the Formats tab. Click on Additional Setting and locate the List Separator. Change the Decimal separator from a full stop (.) to a comma (,).
Both a comma and a period (or full-stop) are generally accepted decimal separators for international use.
Currently, in European countries except for the United Kingdom, the comma is used as the decimal separator. In the United Kingdom, the raised dot is used, and in the United States, the baseline dot is used.
Option 1: using Intl.NumberFormat#formatToParts
Most reliable method, only works for browsers supporting the Intl API. Otherwise it requires an Intl polyfill
function getDecimalSeparator(locale) {
const numberWithDecimalSeparator = 1.1;
return Intl.NumberFormat(locale)
.formatToParts(numberWithDecimalSeparator)
.find(part => part.type === 'decimal')
.value;
}
Option 2: using toLocaleString
Less elegant, it relies on the fact that a separator is always one character long, which seems to be the case for all languages: Decimal separator - Wikipedia
function getDecimalSeparator(locale) {
const numberWithDecimalSeparator = 1.1;
return numberWithDecimalSeparator
.toLocaleString(locale)
.substring(1, 2);
}
This has been suggested here: With a browser, how do I know which decimal separator that the client is using?
Examples:
> getDecimalSeparator()
"."
> getDecimalSeparator('fr-FR')
","
Bonus of option 1:
We could extend it to retrieve either the decimal or group separator of a given locale:
function getSeparator(locale, separatorType) {
const numberWithGroupAndDecimalSeparator = 1000.1;
return Intl.NumberFormat(locale)
.formatToParts(numberWithGroupAndDecimalSeparator)
.find(part => part.type === separatorType)
.value;
}
Examples:
> getSeparator('en-US', 'decimal')
"."
> getSeparator('en-US', 'group')
","
> getSeparator('fr-FR', 'decimal')
","
> getSeparator('fr-FR', 'group')
" "
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With