How would one save a variable that is a Double in to PlayerPrefs? Considering PlayerPrefs only supports string, int, and float?
parseFloat(myDouble);?
Save it as a string (convert it using ToString first), and load it as a string and parse it with double.Parse or System.Convert.ToDouble.
–Eric
im using ToString() to convert my double to string, then SetString to save to the PlayerPrefs, but when using either double.Parse or System.Convert.ToDouble i get a FormatExeption : Invalid Format, when i play in the editor. Im using ToString() but supposedly the exception is due to formatting issues, not sure what could be causing the problem, unless i need to use ToString() differently.
I highly doubt double.ToString() is meant to be used as a proper number serializer. Google around for serializing/deserializing doubles.
EDIT: After further research it turns out that the round trip format specifier will do the trick. In another words, if you pass in “R” as an argument for ToString() then it is guaranteed to be parsed back to the same number.
For the sake of completeness, here’s the complete solution:
/// <summary>
/// Uses SetString()
/// </summary>
public static void SetDouble(string key, double value)
{
PlayerPrefs.SetString(key, DoubleToString(value));
}
public static double GetDouble(string key, double defaultValue)
{
string defaultVal = DoubleToString(defaultValue);
return StringToDouble(PlayerPrefs.GetString(key, defaultVal));
}
public static double GetDouble(string key)
{
return GetDouble(key, 0d);
}
private static string DoubleToString(double target)
{
return target.ToString("R");
}
private static double StringToDouble(string target)
{
if (string.IsNullOrEmpty(target))
return 0d;
return double.Parse(target);
}
You can also use BitConverter.DoubleToInt64Bits to get the actual bits representing the double, use bitwise shifting and masking to split the result into two ints, and store those in the PlayerPrefs.
Nah, not as good because that would require 2 prefs. Mine is just 1.
EDIT: But I must admit that’s a pretty creative solution :). Might try for the hell of it.
Actual storage will be smaller in the general case, and I’m not aware that set pref calls are that expensive. But, hey, if you say so ![]()
Oh no no, both solutions are valid. No one is “right” or “better”. Mine has it’s pros and cons, and yours has its own pros and cons. Both are legitimate ways to solve the problem ![]()
Actually, “R” specifier doesn’t always return the same exact value. For double, use “G17” specifier.