我目前正在为工作建立一个基本网页,并希望包含一个价格计算器。问题是货币在乌干达先令,因此输出数十万和数百万,并将显示为块编号(例如:98635816)。如何插入逗号以使输出数字更容易阅读?
P.S。这是计算器的HTML
<form oninput="y.value=(19657.86*parseInt(b.value)).toFixed(0);
x.value=(928.29*parseInt(b.value)).toFixed(0);
z.value=((y.value)-(x.value)).toFixed(0)">
<input type="number" id="b" value="0">
<output name="y" for="a b"></output>
<output name="x" for="a b"></output>
<output name="z" for="a b"></output>
答案 0 :(得分:2)
您可以使用以下特定代码:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
或javascript的Number.prototype.toLocaleString。 (slower than regex)
var n = 163546872.345
console.log(n.toLocaleString()) // "163,546,872.345"
(!)对于使用node.js或想要在浏览器Numeral.js中有所不同的人可能会感兴趣。
答案 1 :(得分:2)
你可以试试这个:
<form oninput="y.value=numberWithCommas((19657.86*parseInt(b.value)).toFixed(0));
x.value=numberWithCommas((928.29*parseInt(b.value)).toFixed(0));
z.value=numberWithCommas(((19657.86*parseInt(b.value))-(928.29*parseInt(b.value))).toFixed(0))">
<input type="number" id="b" value="0">
<output name="y" for="a b"></output>
<output name="x" for="a b"></output>
<output name="z" for="a b"></output>
<script>
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</script>