Does JavaScript take local decimal separators into account?

前端 未结 7 798
陌清茗
陌清茗 2020-12-10 06:26

I\'ve got a web page that displays decimals in a user\'s localized format, like so:

  • English: 7.75
  • Dutch: 7,75

7条回答
  •  無奈伤痛
    2020-12-10 07:09

    Here's an example for a locale aware number parser:

    function parseLocaleNumber(stringNumber) {
        var thousandSeparator = (1111).toLocaleString().replace(/1/g, '');
        var decimalSeparator = (1.1).toLocaleString().replace(/1/g, '');
    
        return parseFloat(stringNumber
            .replace(new RegExp('\\' + thousandSeparator, 'g'), '')
            .replace(new RegExp('\\' + decimalSeparator), '.')
        );
    }
    

    It uses the current locale of the browser to replace thousand and decimal separators.

    With a German locale setting

    var n = parseLocaleNumber('1.000.045,22');
    

    n will be equal to 1000045.22.

提交回复
热议问题