-5

I have this code:

function sellByte() {
if (player.bytes >= 1) {
    player.bytes = player.bytes - 1;
    player.money = player.money + 0.10;
    document.getElementById("bytes").innerHTML = "Bytes: " + player.bytes;
    document.getElementById("money").innerHTML = "$" + player.money;
   }
}

And whenever I sell a Byte my money value ends up looking like $10.00000003 or something along those lines, how would I go about rounding the money value UP every time this function is run?

Tezma
  • 1
  • 2
  • parseFloat and toFixed are your best friends – Jacobian May 30 '16 at 06:16
  • Do you want to *fix* the rounding errors you get from floating point math, or do you just want to *display* them as rounded numbers? – Jeroen May 30 '16 at 06:17
  • 3
    But actually your question already has answers here at stackoverflow and you should have tied to find them – Jacobian May 30 '16 at 06:17
  • you can refer to this : http://stackoverflow.com/questions/3439040/why-does-adding-two-decimals-in-javascript-produce-a-wrong-result – Kartikeya Sharma May 30 '16 at 06:18
  • There are [*many, many duplicates*](http://stackoverflow.com/search?q=%5Bjavascript%5D+rounding). – RobG May 30 '16 at 06:29
  • There is also this answer for [*Round to at most 2 decimal places*](http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript/12830454#12830454). – RobG May 30 '16 at 06:43

3 Answers3

1

Working with float numbers in JS is very tricky. My suggestion is to operate only with smaller units (cents instead of dollars) and then you will only deal with integers and will not have similar issues.

Goran
  • 3,292
  • 2
  • 29
  • 32
-1

Use Math.round(player.money* 100) / 100 for 2 decimal rounding.

afuc func
  • 942
  • 1
  • 7
  • 12
-1

Use any of the following code

Math.round(num * 100) / 100

using fixed Method

var numb = 123.23454;

numb = numb.toFixed(2);

or you can refer following link for more help

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

Fatima Khan
  • 23
  • 2
  • 5