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