How to handle big numbers in java script

70 views Asked by At

I am trying to make a cookie clicker type game for fun and I ran into a problem. As you get into bigger numbers in a lot of games, cookie clicker for example, the counter doesn't just have a 20 digit number up there, instead it takes the multiple of a thousand i.e.(million, billion, trillion) and so on. I was wondering how I would make this possible so that it can display a drastically high number while still being user friendly and still have the possible math operations applied to it. An important note is that when it passes 1000 of the certain suffix then it rolls over to the next, on the other hand if it goes underneath 1 then it rolls back a multiple of 1000. If anyone has an idea it would be really helpful.

1

There are 1 answers

3
James On

Here's an example using regular javascript numbers. This outputs a number less than a thousand plus a symbol

const map = ["", "K", "M", "B", "T", "Quad", "Quint", "Sext", "Sept", "Oct", "Nov", "Dec"];

const outputAsCookies = (number) => {
  if (number < 1000) return number.toString();

  let log = Math.log10(number);
  let div = log - log % 3;
  let index = div / 3;
  while (index >= map.length) {
    // ran out of map elements
    index -= 1;
    div -= 3;
  }
  
  return (number / Math.pow(10, div)).toPrecision(6) + " " + map[index];
};
console.log(outputAsCookies(100));
console.log(outputAsCookies(1000));
console.log(outputAsCookies(98765432109876));
console.log(outputAsCookies(3.1415926535e32));