-1

In my program, I have a score multiplier variable of type 'Number' When I try to add 0.1 to it, I have a problem. Here is the code:

scoreMultiplier += 0.1;
trace(scoreMultiplier);

scoreMultiplier is originally set to 1, and after the first run through, I correctly get a value of 1.1. However, the second time, the trace shows 1.2000000000000002, and the next time 1.3000000000000003.

There is no other code which modifies scoreMultiplier. This is a problem, first because it is shown on my game screen and goes off the screen, and second because if conditionals where scoreMultiplier==2 for example do not work due to the bizarre fault in the addition.

If anyone knows what's causing this, or at the very least how to truncate the value to 1 decimal place, that would be great.

mpromonet
  • 11,326
  • 43
  • 62
  • 91
Trex
  • 108
  • 9

1 Answers1

1

Flash does not like floating points. At all. Avoid them as much as you can.

djib
  • 656
  • 6
  • 18
  • So there's no workaround? I'm thinking I may just have to add a whole heap of else ifs to check what combo I'm up to and set the score multiplier rather than adding to it unless there's an easier/more efficient way. – Trex May 31 '15 at 07:56
  • 1
    If you add 0.1 each time, consider storing your scoreMultiplier as an int (multiply it by 10) and add 1 each time. You can then divide it by 10 when you need to use it in some calculation. – djib May 31 '15 at 08:00
  • Thanks, this worked. Only thing I had to add is that scoreMultiplier must also start as 10 if using this solution. – Trex May 31 '15 at 08:06
  • You can store all values as ints (so you don't have to multiply by 10 every time you want to do some calculations), but change they way you're displaying it. Add "." before last 2 digits. – 3vilguy May 31 '15 at 12:22