0

I have below program:

double tax = 180.09;
double gTotal = 277.08;

double total = tax + gTotal;

System.out.println(total);

After execution it outputs 457.16999999999996.

After Google search I found that one of the cause for this behavior is that there may be no precise binary representation of the fraction part.

To verify that I tried below:

double dNum = 457.17;
System.out.println(dNum);

It gave correct output as 457.17. In this case, why it is not printing 457.16999999999996.

Vinod
  • 1,076
  • 2
  • 16
  • 33
  • welcome to the floating precision point jungle!!! Check [this answer](http://stackoverflow.com/questions/177506/why-do-i-see-a-double-variable-initialized-to-some-value-like-21-4-as-21-3999996) – Jordi Castilla Mar 30 '15 at 11:04
  • There are at least 100 duplicates of this question. Take a look at the related links to the right – Ivaylo Strandjev Mar 30 '15 at 11:06
  • 2
    The right solution is to use `BigDecimal` in place of `double`. As a general rule, it's a bad idea to use a `double` for calculations with amounts of money. – Dawood ibn Kareem Mar 30 '15 at 11:06
  • maybe [this question](http://stackoverflow.com/q/28395232/217324) has a useful answer. as to *why* the language was designed this way, ask James Gosling. – Nathan Hughes Mar 30 '15 at 11:11

0 Answers0