3

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.

1
  • 1
    have you tried getFloat(0) instead of getInt(0) ? Commented Feb 17, 2016 at 10:07

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

You better save the price as TEXT in the database, and when calculating the sum, cast them to double or BigDecimal for accurate result.

1 Comment

Any consequences of using REAL?
1

Change your return value to double

 public int getTotalOfAmount() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery("SELECT SUM(total_price) FROM " + TOTAL_PRICE, null);
        c.moveToFirst();
        double i = c.getDouble(0);
        c.close();
        return i;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.