0

I computed a number in JavaScript function.

Example:

var price = 1000;
var commission = 200;

var total = price + commission

After I added these two I want to show the total as 1,200 (put , in between 3 digits).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Amila
  • 243
  • 1
  • 10
  • 24
  • Please do a google search before posting the question. http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript – nkm Nov 04 '11 at 11:15
  • possible duplicate of [Format numbers in javascript](http://stackoverflow.com/questions/1068284/format-numbers-in-javascript) – Felix Kling Nov 04 '11 at 11:26

3 Answers3

2

From: http://www.mredkj.com/javascript/numberFormat.html

This functionality is not built into JavaScript, so custom code needs to be used. The following is one way of adding commas to a number, and returning a string.

function addCommas(nStr)
{
    nStr += '';
    x = nStr.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;
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
gamers2000
  • 1,847
  • 2
  • 14
  • 15
  • "It's better to quote the relevant section here and include the link as reference than to only provide the link." Thanks for the heads up Bill, will keep it in mind next time. – gamers2000 Nov 12 '11 at 08:05
0
function addCommas(price) {
    var x = (parseFloat((isNaN(price) ? 0 : price)).toFixed(2)+'').split('.');
    var x3 = x[0].substr(-3);
    for(var i=x[0].length-3; i>0; i=i-3)
        x3 = x[0].substr((i < 3 ? 0 : (i-3)), (i < 3 ? i : 3))+","+x3;
    return x3 + (x.length > 1 ? '.' + x[1] : '');
}

When you do just want an integer value instead of an float with 2 digits, just change the last line to

return x3;
0

often i use toLocaleString depents abit on what im doing (some parts of the world use comma insted of dot and visa for delimiting

var total = (price + commission).toLocaleString()
VeXii
  • 3,079
  • 1
  • 19
  • 25