开发者

having problems adding commas to number while limiting it to only 2 decimal places

开发者 https://www.devze.com 2023-02-12 23:46 出处:网络
function addCommas(nStr) { nStr += \'\'; var x = nStr.split(\'.\'); var x1 = x[0]; var x2 = x.length > 1 ? \'.\' + x[1] : \'\';
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 out开发者_运维技巧put anything.

Thanks


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号