Nodejs String to Currency Convert toCurrency()

Here you can find the source of toCurrency()

Method Source Code

String.prototype.toCurrency = function() {
  /**//from  w ww .  j a va  2s  .co  m
   * Return a currency representation of a String.
   * e.g 11111.11 => 11,111.11
   * Return NaN if the string is non-numerical.
   */
  var isNumberRegex = /^[0-9]+(\.[0-9]+)?$/;
  if (!isNumberRegex.test(this)) {
    return NaN;
  }

  return parseFloat(Number(this).toFixed(2))
    .toString()
    .replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
};

Related

  1. toCurrency()
    String.prototype.toCurrency = function() {
      var pattern = /^\d{4,}/;
      return pattern.test(this) ? parseFloat(this).toLocaleString() : this;
    };
    
  2. toCurrency()
    String.prototype.toCurrency = function(){
      var splitNum = this.split(".");
      var numCurrency = splitNum[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + ("." + splitNum[1]);
      return numCurrency;
    };
    
  3. toCurrency()
    String.prototype.toCurrency = function() {
      var pattern = /(\d)(?=(\d{3})+(?=\.))/g
      return this.toString().replace(pattern, "$1,");
    };
    
  4. toCurrency(rounder)
    String.prototype.toCurrency = function(rounder) {
        aDigits = parseFloat(this).toFixed(rounder).split(".");
        aDigits[0] = aDigits[0].split("").reverse().join("")
                                        .replace(/(\d{3})(?=\d)/g, "$1,").split("").reverse().join("");
        return aDigits.join(".");
    
  5. toCurrency(rounder)
    String.prototype.toCurrency = function(rounder) {
        aDigits = parseFloat(this).toFixed(rounder).split(".");
        aDigits[0] = aDigits[0].split("").reverse().join("")
                                        .replace(/(\d{3})(?=\d)/g, "$1,").split("").reverse().join("");
        return "Rp "+ aDigits.join(".");