0

I am making a project, where im gonna have 6 different numbers, but i want all of them simplified. The problem is when i simplify numbers it takes about 100 lines. So making it 6 times, will give me 600 lines of code just for that.

if (money >= 1000 && money <= 999999){
    moneyshow = money/1000;
    document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" k $";
  }
  if (money >= 1000000 && money <= 999999999){
    moneyshow = money/1000000;
    document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" m $";
  }
  if (money >= 1000000000 && money <= 999999999999){
    moneyshow = money/1000000000;
    document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" b $";
  }
  if (money >= 1000000000000 && money <= 999999999999999){
    moneyshow = money/1000000000000;
    document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" t $";
  }
  if (money >= 1000000000000000 && money <= 999999999999999999){
    moneyshow = money/1000000000000000;
    document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" quad $";
  }
  if (money >= 1000000000000000000 && money <= 999999999999999999999){
    moneyshow = money/1000000000000000000;
    document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" quint $";
  }
  if (money >= 0 && money <= 999 || money >= 1000000000000000000000) {
    moneyshow = money;
    document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+"$";
  }

Is there any way i could simplify that ? Also im gonna need it so i can use it on 6 or more numbers at once.

killereks
  • 189
  • 1
  • 12
  • 2
    Possible duplicate of [How to format a number as 2.5K if a thousand or more, otherwise 900 in javascript?](http://stackoverflow.com/questions/9461621/how-to-format-a-number-as-2-5k-if-a-thousand-or-more-otherwise-900-in-javascrip) – TimoStaudinger Aug 24 '16 at 14:10
  • Turn it into a function so it is reusable. Don't directly alter the HTML of the page, make the function return the number with suffix and then work with that outside of the function – Joseph Young Aug 24 '16 at 14:12
  • You mean, function(number) and inside function, return ? I dont know how return works. Can I do var number = function(number) ? –  killereks Aug 24 '16 at 14:17

1 Answers1

0

Declare 2 variables, inside each if , set these variables to the number you want to divide by and the string you want to append.

var divideBy;
var appendStr;

if (money >= 1000 && money <= 999999)
{
    divideBy = 1000;
    appendStr = "k $";
}

Then at least you can do this just once:

moneyshow = money/ divideBy;
document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+ appendStr;

The beauty of variables in Javascript is that they are not strongly typed.

AsheraH
  • 474
  • 10
  • 15