Java – stores floating point numbers in an Android database
I tried to store dollar amounts in the SQLite database provided by Android, but it didn't seem to work properly This error occurs only when I try to delete a transaction that is not an integer dollar amount I.e. 409.00 will work, but 410.44 will not work
If I store a value like 410.44 and then query the quantity in the database, I can't get a match I tried to use this field as a real data type and a text data type, but it didn't work In the following example, the gettransamount () method returns a float This is the version that runs when I set the DB data type to real Any help will be greatly appreciated thank you.
cv.put(transAmount,t.getTransAmount()); db.insert(tableName,null,cv); x = db.delete(tableName,transAmount + " = " + t.getTransAmount(),null);
Solution
Do not use floating point to store monetary amounts Inaccurate floating point; As you know, floating point comparisons are particularly difficult to handle
I usually store the monetary amount in the database as an integer. For example, 410.44 will be stored as 41044 and 409.00 will be stored as 40900
When you need to convert to 410.44 format for display, you can use the BigDecimal class to pass it the scale to be used (2 in this case), which is the number of decimal places to shift
Example:
int storedAmount = 41044; BigDecimal scaledAmount = new BigDecimal(storedAmount); scaledAmount.setScale(2); // Now contains 410.44