0

Hello i have 3 values in this format 1000, 2000, 200. Iam using this function to convert them in the format below

 function formatNumber(number)
    {
        number = number.toFixed(2) + '';
        x = number.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? ',' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + '.' + '$2');
        }
        return x1 + x2;
    }

1.000,00 2.000,00 and 200,00

How can i calculate them so the result will be 3.200,00 ?

Iam calculating them in each statement beacuase more fields can be generated in my applications.

Thanks. Any help will be appreciated.

mstojanov
  • 175
  • 4
  • 17

1 Answers1

1

Here's a function I adapted from another StackOverflow post a while ago. See the links in the source for more details.

/* 
http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript
decimal_sep: character used as deciaml separtor, it defaults to '.' when omitted
thousands_sep: char used as thousands separator, it defaults to ',' when omitted
*/
Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep) { 
   var n = this,
   c = isNaN(decimals) ? 2 : Math.abs(decimals), //if decimal is zero we must take it, it means user does not want to show any decimal
   d = decimal_sep || '.', //if no decimal separator is passed we use the dot as default decimal separator (we MUST use a decimal separator)

   /*
   according to [http://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]
   the fastest way to check for not defined parameter is to use typeof value === 'undefined' 
   rather than doing value === undefined.
   */   
   t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, //if you don't want to use a thousands separator you can pass empty string as thousands_sep value

   sign = (n < 0) ? '-' : '',

   //extracting the absolute value of the integer part of the number and converting to string
   i = parseInt(n = Math.abs(n).toFixed(c)) + '', 

   j = ((j = i.length) > 3) ? j % 3 : 0; 
   return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); 
}

You can use it like this

var num = 1000 + 2000 + 200;
num.toMoney(2, ',', '.'); // => 3.200,00
alexpls
  • 1,914
  • 20
  • 29
  • Yeah i got it now. Is there any chance to unformatNumber 1.000,00 to the first value 1000 with similar functions ? – mstojanov Jan 13 '15 at 01:56