在jQuery数组循环上用逗号显示数字数据作为钱

时间:2016-11-14 21:32:20

标签: jquery arrays loops object numbers

以逗号显示数字货币数据的任何方式,例如$44,721.90? (没有插件作为jquery-mask首选)

提前致谢。



var name1 = {
  name: "John",
  money: 44721.90
};
var name2 = {
  name: "Mayer",
  money: 16715.79
};

var names = [name1, name2];
   
function show() {
  for (var i = 0; i < names.length; i++) {
    $(".money").append('<span class="name">' + names[i].name + ' </span><span class="budget"> $' + names[i].money + '</span><br>');
  }
}

show();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="money"></div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

这可以帮助

function formatee(num) {
    var dec = "";
    var result = "";
    if(num != parseInt(num)) {
        // get decimal part if exist
        dec = "." + (num+'').replace(/\d+\./, ''); 
    }
    num = parseInt(num);
    while(num > 1000) {
        result = leadZero(num%1000) + (result ? ',' : '') + result;
        num = parseInt(num/1000);
    }
    result = num + (result ? ',' : '') + result + dec;
    return result;
}
function leadZero(numb) {
    return (numb < 100 ? '0':'') + (numb < 10 ? '0':'') + numb;
}

答案 1 :(得分:0)

您可以使用ES6的数字格式方法(see here):

DEMO BELOW:

&#13;
&#13;
var name1 = {
    name: "John",
    money: 44721.90
};
var name2 = {
    name: "Mayer",
    money: 16715.79
};

var names = [name1, name2];

function show() {
    var numFormat = new Intl.NumberFormat("en-US");
    for (var i = 0; i < names.length; i++) {
        $(".money").append('<span class="name">' + names[i].name + ' </span><span class="budget"> $' + numFormat.format(names[i].money) + '</span><br>');
    }
}

show();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="money"></div>
&#13;
&#13;
&#13;

您还可以通过以数字格式(see here)传递样式属性来使用它的货币格式:

以下演示:

&#13;
&#13;
var name1 = {
    name: "John",
    money: 44721.90
};
var name2 = {
    name: "Mayer",
    money: 16715.79
};

var names = [name1, name2];

function show() {
    var numFormat = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
    for (var i = 0; i < names.length; i++) {
        $(".money").append('<span class="name">' + names[i].name + ' </span><span class="budget">' + numFormat.format(names[i].money) + '</span><br>');
    }
}

show();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="money"></div>
&#13;
&#13;
&#13;