Does JavaScript take local decimal separators into account?

前端 未结 7 803
陌清茗
陌清茗 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条回答
  •  Happy的楠姐
    2020-12-10 07:09

    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; }

提交回复
热议问题