Monday, May 20, 2024
30
rated 0 times [  31] [ 1]  / answers: 1 / hits: 17266  / 12 Years ago, fri, august 17, 2012, 12:00:00

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?


More From » localization

 Answers
32

No, the separator is always a dot (.) in a javascript Number. So 7,75 evaluates to 75, because a , invokes left to right evaluation (try it in a console: x=1,x+=1,alert(x), or more to the point var x=(7,75); alert(x);). If you want to convert a Dutch (well, not only Dutch, let's say Continental European) formatted value, it should be a String. You could write an extension to the String prototype, something like:



String.prototype.toFloat = function(){
return parseFloat(this.replace(/,(d+)$/,'.$1'));
};
//usage
'7,75'.toFloat()+'7,75'.toFloat(); //=> 15.5


Note, if the browser supports it you can use Number.toLocaleString





console.log((3.32).toLocaleString(nl-NL));
console.log((3.32).toLocaleString(en-UK));

.as-console-wrapper { top: 0; max-height: 100% !important; }




[#83582] Thursday, August 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jocelynkarsynr

Total Points: 472
Total Questions: 98
Total Answers: 96

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
jocelynkarsynr questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Sat, Jul 11, 20, 00:00, 4 Years ago
Sun, May 10, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
;