ekstro
ekstro

Reputation: 481

How to solve Android SQLite rounding error

We have problem in our Android application with rounding numbers. In calculation made in Java we use BigDecimal and this helps, but we have problem with SQLite, for ex.

SELECT ROUND(150.075 * 100) / 100 (= 150.07, not 150.08!)

Upvotes: 2

Views: 1062

Answers (2)

ekstro
ekstro

Reputation: 481

What you think about this (not elegant) solution:

SELECT ROUND(150.075 + 0.00000000000009, 2) (= 150.08)

We checked it on more then 5 000 incorrect values and it's works good.

Upvotes: 1

laalto
laalto

Reputation: 152827

That's because due to floating point inaccuracies, 150.075 * 100 is not the same as 15007.5. The decimal representation for 150.075 in double-precision floating point is 150.07499999999999999722444243843711.

To get the behavior you want, use the two-argument version of ROUND() which lets you specify the number of decimal digits:

sqlite> SELECT ROUND(150.075, 2);
150.08

Upvotes: 0

Related Questions