Android - SharedPreference 转换为 Double

Android - SharedPreference converting to Double

基本上我有一个值作为字符串保存到共享首选项中。

我正在检索保存的值,并尝试在计算中使用它。

我怎样才能将其转换为双精度而不是字符串?

计算后检索到值后,新值将以相同值保存回共享首选项中。

希望你能理解,一直在纠结这个问题!

            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            String newweight =  sharedPreferences.getString("storednewweight", "");
            newweight = newweight + 5;
            //saves value into sharedpreference
            savePreferences("storednewweight", (Double.toString(newweight)));

只要像我这样写的就可以保存:

双倍多头:

Double.doubleToRawLongBits(double);

长到加倍:

Double.longBitsToDouble(defaultLongValue);

编辑:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Long newweightTemp =  sharedPreferences.getLong("storednewweight", 0L);
Double newWeight = Double.longBitsToDouble(newweightTemp );
newweight = newweight + 5;
//saves value into sharedpreference
sharedPreferences.edit().putLong("storednewweight", Double.doubleToRawLongBits(newWeight)).apply();

类似的东西应该可以做到。

How can i convert this so that it is seen as a double instead of a string?

A) 如果不需要双精度,使用浮点数:getFloat and putFloat.

B) 再次Parse the string as a double then save the double as a string

你可以parse the string as a double:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

String weight =  sharedPreferences.getString("storednewweight", "");
Double newweight = Double.parseDouble(weight);
newweight = newweight + 5;

//saves value into sharedpreference
savePreferences("storednewweight", (Double.toString(newweight)));