Stuart Pegg Stuart Pegg - 1 year ago 66
Javascript Question

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:

  • Dutch:

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
, and the Dutch-formatted addition to return

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

Answer Source

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'));
'7,75'.toFloat()+'7,75'.toFloat(); //=> 15.5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download