Cartesian Theater
Cartesian Theater

Reputation: 1970

Tiny additions to doubles appearing 8 places after decimal: Android

I'm still a bit of a noob regarding this. I'm puzzled about what's happening. I stored a 3.542 in a sqlite database. Checking the database with Firefox sqlite viewer confirmed this. Then I retrieved the value with the following code:

public double getCaffPer(String type) {
    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    builder.setTables(DRKTYPES);
    String[] columns = { MGCAFF };
    String[] selectionArgs = { type };
    Cursor cursor;
    cursor = builder.query(ourDatabase, columns, TYPE + "=?",
            selectionArgs, null, null, null);
    float result = -1;
    if (cursor.getCount() != 0) {
        cursor.moveToFirst();
        result = cursor.getFloat(0);
    }
    cursor.close();
    return result;
}

Debugging revealed a value of 3.542 for result. But then later in my code I call this method:

double caff = helper.getCaffPer(typeName);

and it gives me 3.5420000553131104. I know this isn't much of a difference, but I'm puzzled as to why the stuff at the end is added. Any help would be appreciated.

Upvotes: 0

Views: 103

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83577

The behavior occurs because you declare result as a float but getCaffPer() returns a double. Java does a silent conversion between the two types which introduces the difference in the output.

Upvotes: 4

Related Questions