我有这样一个函数,它将大数转换成更易被人理解的东西: 10,000,000 = 10,000,000,000 = 10B。
然而,一个问题发生时,大量是在100(磨坊,比尔,千分之一)。
20万,000,000转换为0.2吨(万亿),我希望它转换为200 B,而不是十进制格式。这是相同的任何数字在千亿,百万,千,等等.
function convrt(val) {
// thousands, millions, billions etc..
var s = ["", "k", "M", "B", "t"];
// dividing the value by 3.
var sNum = Math.floor(("" + val).length / 3);
// calculating the precised value.
var sVal = parseFloat((
sNum != 0 ? (val / Math.pow(1000, sNum)) : val).toPrecision(2));
if (sVal % 1 != 0) {
sVal = sVal.toFixed(1);
}
// appending the letter to precised val.
return sVal + s[sNum];
} 如何用上面的代码来解决这个问题呢?
发布于 2021-03-14 21:54:30
试着用循环。您可以添加带有数字小数部分的格式。
function convrt(number) {
postfixes = ['', 'k', 'M', 'B', 't']
count = 0
while (number >= 1000 && count < postfixes.length) {
number /= 1000
count++
}
return number + postfixes[count];
} 备注:您可以通过裁剪数字字符串来做到这一点(每个循环都需要删除字符串的最后3个字符,直到字符串长度小于4个字符为止)。但是在这种情况下,如果需要的话,小数部分就会有困难。
发布于 2021-03-14 22:20:42
另一种方法
// Function
const convrt = (n) => {
const matrix = {
"t": 1.0e+12,
"B": 1.0e+9,
"M": 1.0e+6,
"k": 1.0e+3,
"": 1.0e+0
};
// Loop through matrix and return formatted value
for(const k in matrix)
if(Math.abs(Number(n)) >= matrix[k])
return Math.round(Number(n) / matrix[k]) + k;
};
// Demo
console.log(convrt(215));
console.log(convrt(45145));
console.log(convrt(-6845215));
console.log(convrt(92674883122));
console.log(convrt(2192674883122));
https://stackoverflow.com/questions/66629842
复制相似问题