Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

localization - Does JavaScript take local decimal separators into account?

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

  • English: 7.75
  • Dutch: 7,75

If I add two number variables together in JavaScript on my machine (where the numbers are taken from strings in the above formats) I get the following results:

  • English: 7.75 + 7.75 = 15.5
  • Dutch: 7,75 + 7,75 = 0

If I was to run this code on a Dutch users machine, should I expect the English-formatted addition to return 0, and the Dutch-formatted addition to return 15,5?

In short: Does the JavaScript calculation use local decimal separators in its string to number conversions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

function parseLocaleNumber(stringNumber, locale) {
    var thousandSeparator = Intl.NumberFormat(locale).format(11111).replace(/p{Number}/gu, '');
    var decimalSeparator = Intl.NumberFormat(locale).format(1.1).replace(/p{Number}/gu, '');

    return parseFloat(stringNumber
        .replace(new RegExp('\' + thousandSeparator, 'g'), '')
        .replace(new RegExp('\' + decimalSeparator), '.')
    );
}

It uses the passed locale (or the current locale of the browser if locale parameter is undefined) 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.

Update:

  • Addressed Pointy's comment by using the regex class p{Number} for removing digits. So that it also works with non-arabic digits.
  • Addressed Orion Adrian's comment to support languages where numbers are separated at every fourth digits.
  • Added locale parameter to sepcify different locales for parsing.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...