How to add suffixes to an amount of money in javascript

Viewed 82

I have a game where you earn money, and it is very easy to get rich. I want to make it so that if you get money more than a million, instead of showing 1234567, it shows 1.2 million. The process I am trying to go for if the number is more than a million is:

1: get the first two digits

2: remove the first two digits

3: store the remaining digits into a list

4: divide the length of the list by 3

5: get that value in the list of suffixes - 1 (because lists start at 0, not 1)

I can make the list of suffixes, I just need help on how to make this process.

3 Answers

This might be a good starting place for you. Let me know if it helps.

const $ = s => [...document.querySelectorAll(s)];

function formatNumber(n) {
  if (n > 10**9 - 1) {
    return (n / 10**9).toFixed(2) + "b"
  } else if (n > 10**6 - 1) {
    return (n / 10**6).toFixed(2) + "m"
  } else {
    return n
  }
}


$("button")[0]
.addEventListener("click", e => {
  const userInput = $("input")[0].value;
  const formattedNumber = formatNumber(userInput);
  $("#display")[0].innerText = formattedNumber;
});
body {
  font-size: 2em;
  }
<input type="number">
<button>Go</button>

<div id="display">output</div>

Here's an efficient approach that doesn't require any parsing - just simple string manipulation:

  • Get the digits greater before the 6 digit mark by subtracting the length of the string by 6

  • For the digit immediately after the 6 digit mark, you can use charAt and get the character at the index of the length of the string minus 6

Result:

const num = "13356789";

function wordify(number) {
  if (number.length > 6) {
    const start = num.substring(0, number.length - 6);
    const second = num.charAt(number.length - 6);
    return `${start}.${second} million`;
  }
}

console.log(wordify(num));

Try it yourself with custom numbers:

function wordify(number) {
  if (number.length > 6) {
    const start = number.substring(0, number.length - 6);
    const second = number.charAt(number.length - 6);
    return `${start}.${second} million`;
  }else{
    return `number must have at least 6 digits`;
  }
}

num.addEventListener('input', () => {
  result.innerHTML = wordify(num.value);
});
Enter a number: <input id="num" type="number"><br/><br/> Result: <span id="result"></span>

Handling all cases (thousands, millions and billions):

let money = 1234567;
let strMoney = String(money);

if(strMoney.length >= 7 && strMoney.length <= 9) {
  console.log(Math.round(money/ 1000000 * 100)/100, 'million')
}else if(strMoney.length > 9) {
  console.log(Math.round(money/ 1000000000 * 100)/100, 'billion')
}else if(strMoney.length <= 6 && strMoney.length >= 4){
  console.log(Math.round(money/ 1000 * 100)/100, 'thousand')
}else {
  console.log(money)
}

Related