How can I preserve Double precision when saving values in Android SharedPreferences?


I'm developing an Android expense tracking application using Kotlin.

In my registration activity, I receive the user's monthly salary as a Double, but I save it in SharedPreferences as a Float:

val salarioNumero = salario.text.toString().toDoubleOrNull()

// After validating the input:
preferencias.edit()
    .putFloat("salario", salarioNumero.toFloat())
    .apply()

In my DashboardActivity, I retrieve the salary either from an Intent or from SharedPreferences:

salario = if (intent.hasExtra("salario")) {
    intent.getDoubleExtra("salario", 0.0)
} else {
    preferencias.getFloat("salario", 0f).toDouble()
}

I tested my application with a salary of 4500.80, and the dashboard displayed the expected amount. However, I noticed that converting a Double to Float may cause precision loss that is not visible when formatting the result to two decimal places.

I understand that SharedPreferences does not provide putDouble() or getDouble() methods.

What is the appropriate way to persist and retrieve the Double value without the additional precision loss caused by converting it to Float?

I would also like to understand whether storing monetary amounts as Double is appropriate for an expense tracking application.

-3
Oct 29 at 4:00 AM
User AvatarGesler Duque
#android#kotlin#sharedpreferences

Accepted Answer

Save the value:

val salary = salaryEditText.text.toString().toDoubleOrNull()

if (salary != null) {
    preferences.edit()
        .putString("salary", salary.toString())
        .apply()
}

Retrieve the value:

val salary = preferences
    .getString("salary", "0.0")
    ?.toDoubleOrNull() ?: 0.0
User AvatarDhruv Sakariya
Oct 29 at 6:34 AM
1