Can’t put double SharedPreferences

Those who suggested to use putFloat and getFloat are unfortunately very wrong. Casting a double to a float can result in

  1. Lost precision
  2. Overflow
  3. Underflow
  4. Dead kittens

Those suggesting a toString and parseString are not wrong, but it’s an inefficient solution.

The correct way of dealing with this is to convert the double to its ‘raw long bits’ equivalent and store that long. When you’re reading the value, convert back to double.

Because the two data types have the same size you don’t lose precision and you won’t cause an {over,under}flow.

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 write the getter 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));
}

Leave a Comment