Crazy Floating Point Error

Hi Guys,

I have a float that starts at 1. Let’s just say it represents a progress bar.

When my player gets hit, and his health decrements, i decrement by 0.01 until all the damage has been applied.

The code is very simple, it looks like this:

if (healthToShow < playerHealth.Value)
playerHealth.Value -= 0.01;

However - when the value decrements from 0.95 to 0.94, instead of getting 0.94, i get 0.9400001
when the value gets to 0.8500001, it then decrements to 0.8400002.

I tried this multiple ways, including making a simple floating point value and just decrementing it for no reason. It ALWAYS does this.

Does anyone know why this is happening? or what kind of code to add to force the floating point value to accept only the first 3 digits?

It’s due to rounding errors, floating point numbers arnt stored like int values, so sometimes they cant actually represent the exact value you need it’s expected behavior so you either use an int or a double or scale your result up or redo your logic so such things don’t matter.

A floating point number doesn’t have enough decimal places to accurately represent every number. It is only approximately accurate most of the time. If you want exact numbers you should try using fixed point math… e.g. instead of storing 1, store 100, then when you want to add 0.1 to it, add 10 to it. Then when you want to display it, divide it by 100.

As mentioned, it’s not a ‘crazy error’; it’s just how floating-point representations work. If the error is causing problems for you, you’ll just need to revise your code accordingly. (There are various ways you can work around and/or compensate for floating-point error - the posts above include a couple of suggestions as to how you might do so in this case.)