Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting sum total of column values in SQLite

Tags:

android

sqlite

I have a table in SQLite with this structure:

 String CREATE_TOTAL_PRICE = "CREATE TABLE " + TOTAL_PRICE + "("
                + KEY_TPID + " INTEGER PRIMARY KEY,"
                + KEY_TPRICE + " REAL" + ")";

I am trying to get the sum total of all column values of column KEY_TPRICE. I am using this method which seems to work:

 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 comes when the value is being displayed.

You see i have data input as 50.01,5.5 and when getting the sum total i get 55 which is not really the case.

The real total is 55.51 when i run the query externally.

I have tried setting REAL,INTEGER, FLOAT,DOUBLE as my column data type but still

What exactly is rounding up my figures? Please asssist me with suggestions.

like image 905
Steve Kamau Avatar asked Nov 21 '25 11:11

Steve Kamau


1 Answers

I think you are receiving 55 because you are reading it as "int"

int i = c.getInt(0);

That's why it is being "converted" to int (55).

According to question https://stackoverflow.com/a/17947203/4860513 , it seems that SUM() will return a number in the same format of the column that you are reading. So, try it to read is a double/float and share the result:

 float i = c.getFloat(0);
 double i = c.getDouble(0);
like image 82
W0rmH0le Avatar answered Nov 23 '25 15:11

W0rmH0le



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!