Reputation: 1766
I have this function that converts large numbers into something more readable to the human eye: 10,000,000 = 10M 10,000,000,000 = 10B
However an issue occurs when the large number is at a hundred(mill, bill, thousandth).
200,000,000,000 converts to 0.2 t (trillion) , I would like it to convert to 200B, instead of the decimal format. This is the same any number in the hundredth billion, million, thousand, etc...
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];
}
How can I fix that with my code above?
Upvotes: 0
Views: 495
Reputation: 2549
Another approach
// 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));
Upvotes: 1
Reputation: 436
Just try to use the loop. You can add format with decimal part of number.
function convrt(number) {
postfixes = ['', 'k', 'M', 'B', 't']
count = 0
while (number >= 1000 && count < postfixes.length) {
number /= 1000
count++
}
return number + postfixes[count];
}
Note. You can do this by cutting the number string (every loop you need to strip the last 3 characters of the string until the length of the string is less than 4 characters). But in this case, you will have difficulty the decimal part, if you need it.
Upvotes: 3