如何将数字字符串格式化为适当本地化的显示格式?
How to format a number string to an appropriately localized display format?
我有调用 API:
的代码
<script>
setInterval(function(){ getPrintCount(); }, 1500);
function getPrintCount(){
$.ajax({
url: 'https://data.memopresso.com/api/data/count',
dataType: 'json',
type: 'get',
cache: false,
success: function(data){
document.getElementById("printCount").innerHTML = data.count;
},
error: function(data){
document.getElementById("printCount").innerHTML = '0';
}
});
}
我想让它输出格式为 9,55,100(印度格式)的数字。
我找到了
.toLocaleString('en-IN')
应该可以解决我的问题。
我试着像这样把它放到我的代码中
document.getElementById("printCount").innerHTML = data.count.toLocaleString('en-IN');
但我做不到,
数字仍然显示为纯文本
好像要用toLocaleString
显示号码,号码必须是Number
,而不是String
。您的 data.count
似乎被视为 String
。请尝试以下操作:
document.getElementById("printCount").innerHTML = parseInt(data.count).toLocaleString('en-IN');
或者,如果您的数字是浮点数:
document.getElementById("printCount").innerHTML = parseFloat(data.count).toLocaleString('en-IN');
我有调用 API:
的代码<script>
setInterval(function(){ getPrintCount(); }, 1500);
function getPrintCount(){
$.ajax({
url: 'https://data.memopresso.com/api/data/count',
dataType: 'json',
type: 'get',
cache: false,
success: function(data){
document.getElementById("printCount").innerHTML = data.count;
},
error: function(data){
document.getElementById("printCount").innerHTML = '0';
}
});
}
我想让它输出格式为 9,55,100(印度格式)的数字。
我找到了
.toLocaleString('en-IN')
应该可以解决我的问题。
我试着像这样把它放到我的代码中
document.getElementById("printCount").innerHTML = data.count.toLocaleString('en-IN');
但我做不到, 数字仍然显示为纯文本
好像要用toLocaleString
显示号码,号码必须是Number
,而不是String
。您的 data.count
似乎被视为 String
。请尝试以下操作:
document.getElementById("printCount").innerHTML = parseInt(data.count).toLocaleString('en-IN');
或者,如果您的数字是浮点数:
document.getElementById("printCount").innerHTML = parseFloat(data.count).toLocaleString('en-IN');