0

I am trying to write a quick script that will update a spans text every 1 second to add a random amount of money to the amount. This issue I am facing is the randomNumber variable returns lots of decimal places and doesn't seem to be doing what I want. I just want to add a random number of £0.03 pence to £6.43 added on to the existing number. Is there a way to stop it outputting decimal numbers like 10.333333333333333333 and so on? and possibly just make it more robust and output the correct value.

var number = 0;
setInterval(function(){ 
    var randomNumber = Math.floor(Math.random() * (6.43 - 0.3 + 1)) + 0.3;
    number += randomNumber;
    document.getElementsByClassName("currency")[0].textContent = "£" + number;
}, 1000);
  • use this expression: number += randomNumber.toFixed(2) or better: document.getElementsByClassName("currency")[0].textContent = "£" + number.toFixed(2) – volkinc Aug 10 '17 at 15:13
  • 1
    store £6.43 in pence as 643 and only convert to pounds and pence for display. That makes things much simpler: `var randomNumber = Math.floor(Math.random() * (643 - 3 + 1)) + 3;` and `.textContent = "£" + number / 100;` – Alex K. Aug 10 '17 at 15:14

0 Answers0