Those who suggested using putFloat and getFloat, unfortunately, are very mistaken. Bringing the double to the float may result in
- Lost accuracy
- Overflow
- Underflow
- Dead kittens
Those that offer toString and parseString are not mistaken, but this is an inefficient solution.
The right way to handle this is to convert the double to its raw long bits equivalent and keep it long. When you read the value, convert back to double.
Since the two types of data are the same size, you will not lose accuracy, and you will not call the {over, under} stream.
Editor putDouble(final Editor edit, final String key, final double value) { return edit.putLong(key, Double.doubleToRawLongBits(value)); } double getDouble(final SharedPreferences prefs, final String key, final double defaultValue) { return Double.longBitsToDouble(prefs.getLong(key, Double.doubleToLongBits(defaultValue))); }
Alternatively, you can record the recipient as:
double getDouble(final SharedPreferences prefs, final String key, final double defaultValue) { if ( !prefs.contains(key)) return defaultValue; return Double.longBitsToDouble(prefs.getLong(key, 0)); }
copolii Aug 07 '13 at 8:13 2013-08-07 08:13
source share