[英]How to add thousand separator to a String with JS or JQuery in this particular function?
[英]How to add a thousand separator to a JS number for string output?
我有一個venue_capacity
呼叫正在進行,它將足球隊的場地容量作為沒有千位分隔符的數字返回。 我想將其打印為字符串並包含千位分隔符。
我的想法是在獲得來自 API 的數據后運行 function 以相應地操作變量venue_capacity
。
這是我當前的嘗試(來自此線程: 如何在 JavaScript 中使用逗號打印一個數字作為千位分隔符),它返回不帶分隔符的圖形:
$.ajax({
method: "GET",
async: "True",
dataType: "json",
url: "https://cors-anywhere.herokuapp.com/https://www.api-football.com/demo/api/v2/teams/team/" + team_id,
success: function(response) {
var team_info = response;
console.log(team_info);
team = team_info.api.teams[0].name;
founded = team_info.api.teams[0].founded;
venue_capacity = team_info.api.teams[0].venue_capacity;
function numberWithCommas(venue_capacity) {
return venue_capacity.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
$("#selectedClub").html(team);
$("#founded").html(founded);
$("#venue_capacity").html(venue_capacity);
}
您不必在$.ajax
的 scope 中聲明function
s - 只需一次性執行翻譯:
venue_capacity = team_info.api.teams[0].venue_capacity.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
嘗試使用此 function 代替:
function formatWithCommat(x){
return x.toLocaleString('en-GB');
}
您可以在此處找到有關它的更多信息https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.