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);
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.44would be stored as41044, and409.00as40900.When you need to convert to the
410.44format for display, you can use theBigDecimalclass, passing it the scale to use (2 in this case) which is the number of digits to shift the decimal point by.Example: