How do I find the decimal separator for current locale in Javascript

后端 未结 1 1120
长情又很酷
长情又很酷 2020-12-19 11:09

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

相关标签:
1条回答
  • 2020-12-19 11:37

    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')
    " "
    
    0 讨论(0)
提交回复
热议问题