Android – get the sum of column values in SQLite
I have a table in SQLite with the following structure:
String CREATE_TOTAL_PRICE = "CREATE TABLE " + TOTAL_PRICE + "("
+ KEY_TPID + " INTEGER PRIMARY KEY,"
+ KEY_TPRICE + " REAL" + ")";
I'm trying to get key_ The sum of all column values of tprice column. I am using this seemingly effective method:
public int getTotalOfAmount() {
sqliteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT SUM(total_price) FROM " + TOTAL_PRICE, null);
c.moveToFirst();
int i = c.getInt(0);
c.close();
return i;
}
But the problem is when the value is displayed
You can see that the data I entered is 50.01,5.5. When I get the total, I get 55. This is not the case
When I run the query externally, the actual total is 55.51
I tried to set real, integer, float and double as my column data type, but still
What is my number? Please give me some advice
resolvent:
I think you received 55 because you read it as "int"
int i = c.getInt(0);
This is why it is "converted" to int (55)
According to the problem https://stackoverflow.com/a/17947203/4860513 , it seems that sum() will return a number in the same format as the column you are reading. Therefore, try reading it as double / float and sharing the result:
float i = c.getFloat(0);
double i = c.getDouble(0);