Domanda

When i want to calculate

0.9623 - 0.9619

it returns:

4.0000000000006697E-4

Why is that? and how can i avoid this? I tried casting to float but didn't helped.

  System.out.println(0.9623 - 0.9619);

prints to console:

4.0000000000006697E-4

È stato utile?

Soluzione

It prints the correct answer. 4.0000000000006697E-4 is 4.0000000000006697 * 10^(-4) which is 0.0004, your expected answer.

You could use DecimalFormat df = new DecimalFormat("#.####"); to make the compiler show just four decimal places. Here is a good example

Altri suggerimenti

This is normal.

You are returning a double in scientific notation. The println method in this case will print out the equivalent of String.valueOf(yourDoubleValue)

Real literals are implicitly interpreted as primitive doubles unless specified otherwise.

To force interpretation to float you need to append f to your literals, although it won't change the fact that your result will be printed in scientific notation and with possible loss of precision:

System.out.println(0.9623f - 0.9619f);

Output

4.0000677E-4

I suspect what you ultimately want to print is:

System.out.println(new BigDecimal("0.9623").subtract(new BigDecimal("0.9619")).toPlainString());

Output

0.0004

More on BigDecimal here.

I don't know the context of your code but if decimals are important in your case, I would consider using BigDecimal especially if it's for financial apps. You can configure the rounding mode and have a better precision.

Use System.out.printf("%.4f",0.9623 - 0.9619); which will print the number with 4 decimal places. BigDecimal does tend to be overkill, and has a significant time penalty if you are doing a lot of mathematical calculations.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top