Storing floating point numbers in android database Storing floating point numbers in android database sqlite sqlite

Storing floating point numbers in android database


Don't use floating-point to store currency amounts. Floating-point is inaccurate; as you have found out, floating-point comparisons are especially tricky to deal with.

I normally store currency amounts in the database as integers, e.g. 410.44 would be stored as 41044, and 409.00 as 40900.

When you need to convert to the 410.44 format for display, you can use the BigDecimal class, passing it the scale to use (2 in this case) which is the number of digits to shift the decimal point by.

Example:

int        storedAmount = 41044;BigDecimal scaledAmount = new BigDecimal(storedAmount);scaledAmount.setScale(2);  // now contains 410.44