2016-11-14 51 views
0

任何使用逗號顯示數字貨幣數據的方法$44,721.90? (沒有插件作爲jquery面膜的首選)在jQuery數組循環中以逗號顯示數字數據

在此先感謝。

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();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="money"></div>

+0

可能[如何正確使用jQuery格式化貨幣?](http:// stac koverflow.com/questions/5043650/how-can-i-correctly-format-currency-using-jquery) – Santi

回答

0

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

DEMO下圖:

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();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="money"></div>

您還可以使用它的貨幣格式傳遞一個樣式屬性的數字格式(see here):

DEMO下圖:

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();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="money"></div>

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