- Home /
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!
Answer by Bunny83 · Feb 21, 2020 at 03:18 AM
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.
Thank You! This was exactly the answer I needed! All I had was 11 points, but I sent them over as a thank you.
Here's the final code for anybody who may need it:
int kills = PlayerPrefs.GetInt("Current$$anonymous$$ills");
int shotsfired = PlayerPrefs.GetInt("ShotsFired");
float fPrecision = ((float)kills / shotsfired) * 100; //percentage!
int iPrecision = (int)fPrecision;
PlayerPrefs.SetInt("Precision", iPrecision);
It worked perfectly!
Your answer
Follow this Question
Related Questions
Cannot implicitly convert type `float' to `int 1 Answer
C# Int to Float conversion performance 3 Answers
How to use PlayerPrefs 4 Answers
problem with playerprefs 1 Answer