Reputation: 9049
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
P = addCommas(P);
$("#monthly_result").html(P.toFixed(2));
I left out the P calculations, so keep in mind it is outputting a number in the thousands with decimals.
I got the function from stack and it works well adding commas to numbers in the thousands. However when I tried to limit the value to 2 decimal places it doesnt output anything.
Thanks
Upvotes: 0
Views: 1048
Reputation: 542
toFixed is not available for strings (which your addCommas function returns). simple solution would be to convert the number to a float by using parseFloat and then cut the decimal places using toFixed and convert back to string to proceed with your function.
for a fixed number of decimal places, something along the lines of:
function addCommas(num) {
var num = parseFloat(num).toFixed(2)+'',
rgx = /(\d+)(\d{3}[\d,]*\.\d{2})/;
while (rgx.test(num)) {
num = num.replace(rgx, '$1' + ',' + '$2');
}
return num;
}
In this case, addCommas(61423.34512);
would return "61,423.35"
. I'd recommend using the number_format function posted by Robert for some extra formatting options, though.
Upvotes: 0
Reputation: 57278
my answer is pretty simple but would be what your looking for:
http://phpjs.org/functions/number_format:481
Example:
$("#monthly_result").html(number_format('1234.56', 2));
Upvotes: 1