Search code examples
androidsqliteformattingdoublefractions

Can I convert a fraction to a string using Double.toString(3 + 1/3)?


I have some code that's setting some static database values. One of the values I want to set is 3 and a third. Below is a shortened versioin of what I was trying to do.

 String str = Double.toString(3+1/3);
ContentValues values = new ContentValues();
values.put(KEY_MY_VALUE, str);

db.insert(TABLE_MYTABLE, null, values);

But it shows up in the table merely as "3" whereas I would have expected "3.3333333...."


Solution

  • To do the division without truncation, you have to use at least some floating-point number:

    str = Double.toString(3 + 1.0 / 3);
    

    But if you want the string in a specific format, you could just use that format in the first place:

    values.put(KEY_MY_VALUE, "3.3333333333333333");
    

    And if that value is later used as a number, not as a string, you should store it as a number in the database:

    values.put(KEY_MY_VALUE, 3 + 1.0 / 3);