Reputation: 3313
I'm trying to store dollar amounts in the sqlite database provided by android but it doesn't seem to work properly. This error only occurs when I try to remove a transaction that aren't whole dollar amounts. i.e. 409.00 will work but 410.44 won't.
If I store a value such as 410.44 and then query the database for that amount I don't get a match. I've tried to use this field as the REAL datatype and the TEXT datatype but neither works. In the following example the getTransAmount() method returns a float. This is the version i ran when I had the db datatype as REAL. Any help would be appreciated. Thanks.
cv.put(transAmount, t.getTransAmount());
db.insert(tableName, null, cv);
x = db.delete(tableName, transAmount + " = " + t.getTransAmount(), null);
Upvotes: 3
Views: 1674
Reputation: 60721
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
Upvotes: 7