Javascript数字缩写为KMBTPE
代码:
function intToString(num) {
num = num.toString().replace(/[^0-9.]/g, '');
if (num < 1000) {
return num;
}
let si = [
{v: 1E3, s: "K"},
{v: 1E6, s: "M"},
{v: 1E9, s: "B"},
{v: 1E12, s: "T"},
{v: 1E15, s: "P"},
{v: 1E18, s: "E"}
];
let index;
for (index = si.length - 1; index > 0; index--) {
if (num >= si[index].v) {
break;
}
}
return (num / si[index].v).toFixed(2).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1") + si[index].s;
}
示例代码:
<input type="number" value="1200" id="input-number">
<button type="button" id="convert">Convert</button>
<div id="result">1.2K</div>
<script>
document.getElementById("convert").addEventListener("click", function(){
var number_val = document.getElementById("input-number").value;
var result = intToString(number_val);
document.getElementById("result").innerHTML = result;
});
</script>
版权声明:本文为原创文章,版权归 全栈开发技术博客 所有。
本文链接:https://www.lvtao.net/dev/javascript-num-format.html
转载时须注明出处及本声明