Using .toLocaleString() in Node.js

前端 未结 4 1755
被撕碎了的回忆
被撕碎了的回忆 2020-12-15 04:14

So I was writing a small helper method to convert numbers into a valid money format ($xx,xxx.xx) using .toLocaleString(). Everything works as expe

4条回答
  •  隐瞒了意图╮
    2020-12-15 04:59

    Just in case someone else stumbles upon this, here's how I formatted a number into a valid US dollar string while in a Node.js environment.

    Number.prototype.toMoney = function() {
      var integer = this.toString().split('.')[0];
      var decimal = this.getDecimal();
    
      integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    
      if( !decimal || !decimal.length ) {
        decimal = "00";
      } else if ( decimal.length === 1) {
        decimal += '0';
      } else if ( decimal.length > 2 ) {
        decimal = decimal.substr(0, 2);
      }
    
      return '$' + integer + '.' + decimal;
    };
    
    Number.prototype.getDecimal = function() {
      var n = Math.abs(this);
      var dec = n - Math.floor(n);
      dec = ( Math.round( dec * 100 ) / 100 ).toString();
    
      if( dec.split('.').length ) {
        return dec.split('.')[1];
      } else return "";
    };
    

    There are a few boo-boo's here, namely extending the native Number prototype. You will want to avoid this is 90% of the time; this is more specific to my particular implementation.

    I blatantly stole the regex for formatting the commas from this question. and hacked together the decimal support of my own volition. Mileage may vary.

提交回复
热议问题