0

Possible Duplicate:
Moving decimal places over in a double

I have a problem in my android application using double variables. An EditText parses a number, a double, and puts it in sql database. When I extract that value and I sum with other values the result is incorrect.

For example:

  • I write and put in my db this: 64.1
  • another value: 12.6
  • another value: 400

then I sum these 2 values and the result is 476.70000000000005 wich is incorrect (should be 476.7).

How can I resolve this problem?

Community
  • 1
  • 1
  • You can declare the result value(Adding three value) to float.. – Subburaj Jan 28 '13 at 10:28
  • 5
    This is not a problem in your code, it is a problem with your expectations of floating-point arithmetic. There are many many questions, and answers, on SO about this topic. I suggest you review some of them. – High Performance Mark Jan 28 '13 at 10:28
  • @Subburaj How is using float going to solve a precision issue? – assylias Jan 28 '13 at 10:29
  • @assylias anyway it will cut the precision value to some extent.. – Subburaj Jan 28 '13 at 10:35
  • [This article](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) may interest you. Also using `BigDecimal` is good way to solve this problem. – Pshemo Jan 28 '13 at 10:41

1 Answers1

2

use this function:

double roundTwoDecimals(double d) {
            DecimalFormat twoDForm = new DecimalFormat("#.##");
        return Double.valueOf(twoDForm.format(d));
}
Vikram Singh
  • 1,420
  • 14
  • 19