0
timedLoop(10000, function() {
  health=health-0.1;
  updatecounters();
  console.log(health);
});

Health is initially set to 83.3 and console.log prints out the following statements:

83.2
83.10000000000001
83.00000000000001
82.90000000000002
82.80000000000003
82.70000000000003
82.60000000000004
82.50000000000004
82.40000000000005

It's supposed to be decreasing by 0.1 every 10 seconds, but there seems to be a floating point error. I know that I can fix this by simply rounding the variable to 2 decimal places, but why does this happen?

I think that this is just shitty compiling. If a number has a terminating decimal (less than 32 digits) or is rational, the program should be able to store the exact value instead of making shenanigans like these happen. I fully understand why multiplication and division induce floating point errors, but addition and subtraction should not cause bugs like these.

cweiske
  • 30,033
  • 14
  • 133
  • 194
Display name
  • 257
  • 2
  • 8

3 Answers3

0

You can called .toFixed on the number after the subtraction.

let health = 83.3;

setInterval(function() {
  health = (health - 0.1).toFixed(1);
  console.log(health);
}, 500);

However, .toFixed will convert the number to a string, if you need to keep it as a number, you can wrap the code with the number constructor:

Number((health - 0.1).toFixed(1));
KevBot
  • 17,900
  • 5
  • 50
  • 68
0

The issue is not with javascript but it applies to all floating point calculations since 0.1 and 0.2 and 0.3 are not exactly representable.

Check this link to know more about it

brk
  • 48,835
  • 10
  • 56
  • 78
0

Floating point issues are just part of life. You need to learn to live with them.

You could try:

// health (String) is for display, can be values from 100.0 to 0.1
var health = "100.0";
// healthMath (Int) is for calculations. It is an int, not a float. 
var healthMath = 1000;

So, in your example:

timedLoop(10000, function() {
  healthMath -= 1;
  health = (healthMath / 10).toFixed(1);
  updatecounters();
  console.log(health);
});
Tigger
  • 8,980
  • 5
  • 36
  • 40