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 currencie
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')
" "