Converting from an Int to a Float and back with PlayerPrefs

Hello, I’m having a weird issue. I’ve been looking around for a couple hours and I feel like I’m losing my mind.

I’m trying to create a PlayerPref based on two other Prefs, and it’s just not working right.

int kills = PlayerPrefs.GetInt("CurrentKills");
int shotsFired = PlayerPrefs.GetInt("ShotsFired");

float fPrecision = kills / shotsFired;

int iPrecision = (int)fPrecision;

PlayerPrefs.SetInt("Precision", iPrecision);

I saw a post that was using ToString, but I have no idea how to make it work!

floatValue.ToString("0");

I don’t get it. Am I supposed to put something where the zero is? Or what? I just see a lot of people saying, “Hey, it worked for me!” but nobody actually shows how to implement it. Thanks in advance!

I guess that “kills” will always be less or equal to “shotsFired”. This expression:

kills / shotsFired;

will not produce a float value. Since both operands are integer values this will perform an integer division and the result is also an integer. As soon as shotsFired is greater than kills this expression will always be 0. Only when both values are the same you would get a value of 1.

In order to perform a floating point division at least one of the operands need to be a float value.

float fPrecision = (float)kills / shotsFired;

Of course if your precission is less than 1.0 casting the float value back into an integer will of course again result in a value of 0. For example if you have 30 kills and 48 shots fired you get a float value of “0.625” (so about 62.5 percent). However casting 0.625 into an integer will floor the value back to “0”. Maybe you wanted the value in actual percent? If that’s the case you have to multiply your ratio by 100.