Damage calculation seems off when dealing with decimals

Hello community


I’m having troubling finding out why my calculations seems off, when receiving damage, and the damage being 0.2.
As you can see on the picture below, at some point my HP will have an insane decimal number.

125043-health.png


My damage calculation is a basic: health -= damage; where both variables are floats.

From test it seems after the 5th hit, I will end up with x.000001
I’m rather new to Unity, but is that just how floats works ?


I tried to resort to double, but I use Vectors in some calculations in terms of knockback and healthbar, so I don’t think it would be wise of me to redo all my floats to doubles, as then I would have to find another way to convert Vector3 to doubles, which I don’t know is possible rn.


I tried to do on my take damage formulas the following, but didn’t yield any changes:

   public void TakeDamage(float damage, Vector3 playerpos)
    {
        health = (health * 100f) / 100F;
        damage = (damage * 100f) / 100f;
        health -= damage;
        // knock back
        Vector2 knockbackPosition = (transform.position - playerpos).normalized * knockbackForce; 

        GetComponent<Rigidbody2D>().velocity = knockbackPosition;
   
    }

Kind regards
DaPham

You’re right, it is just how floats work. Can’t you work on ints instead? You could keep your health and damage values as integers with 10 times bigger value (in your example, 22 health points and 2 points of damage) and only convert them to floats when you need to display them to the player.