I need some help with my function. I am new to coding and this task is part of Coderslang apprentice level tasks.
Implement a function that If n < 1000, it should be rounded to a single digit after a decimal point Else, to cut down the length of a number, we need to use letters 'K', 'M', 'B', 'T' to represent thousands, millions, billions or trillions. We're not really interested in being super precise here. If the number exceeds 999.99T it becomes 1.00aa, after 999.99aa goes 1.00ab. When the number gets as high as 999.99az it will next turn into 1.00ba and so on.
The bold text is where I am having an issue, I am not sure how best to write this function and need help. Below is what I have tried so far but I am failing two parts of the test- The function formatNumber should work properly for numbers less than 999az. And the function formatNumber should not cut trailing zeros.
My code so far:
export const formatNumber = (n) => {
let number = n;
let suffix = [97, 92];
let newNumber = "";
if (n < 1000) {
return n.toFixed(1);
} else if (n < 1000000) {
return (n / 1000).toFixed(2) + 'K';
} else if (n < 1000000000) {
return (n / 1000000).toFixed(2) + 'M';
} else if (n < 1000000000000) {
return (n / 1000000000).toFixed(2) + 'B';
} else if (n < 1000000000000000){
return (n / 1000000000000).toFixed(2) + 'T';
}
while (number > 1000) {
(number /= 1000);
if (suffix[1] < 122) {
suffix[1]++;
} else {
suffix[0]++;
suffix[1] = 97
}
}
const stringNumber = String(number);
const i = stringNumber.indexOf(".");
if (i >= 0) {
newNumber = stringNumber.substring(0, i) + "." + stringNumber.substring(i + 1, i + 3);
} else {
newNumber = stringNumber + ".00";
}
return newNumber + String.fromCharCode(suffix[0]) + String.fromCharCode(suffix[1]);
}
I have searched this forum and others and am struggling, any help would be appreciated. I feel that either I am over complicating the thought process or I'm missing something obvious. Is it my while loop? I have tried number.toFixed and number.toExponential without luck
It was a very simple fix, I was over complicating this.
export const formatNumber = (n) => {
let number = n;
let suffix = [97, 92];
let newNumber = "";
if (n < 1000) {
return n.toFixed(1);
} else if (n < 1000000) {
return (n / 1000).toFixed(2) + 'K';
} else if (n < 1000000000) {
return (n / 1000000).toFixed(2) + 'M';
} else if (n < 1000000000000) {
return (n / 1000000000).toFixed(2) + 'B';
} else if (n < 1000000000000000){
return (n / 1000000000000).toFixed(2) + 'T';
}
while (number > 1000) {
(number /= 1000);
if (suffix[1] < 122) {
suffix[1]++;
} else {
suffix[0]++;
suffix[1] = 97
}
}
newNumber = number.toFixed(2);
return newNumber + String.fromCharCode(suffix[0]) + String.fromCharCode(suffix[1]);
}```