1
double  x = 0.00090; 
double b = 0.00100;
double c = x - b;

produces

-1.0000000000000005E-4

instead of

-0.0001

and

double  x = -0.09;       
double b = 0.001;
double c = x * b;

produces

-8.999999999999999E-5

instead of

-0.00009

I also tried with

Math.round(c) and Math.round(c*100.0)/100.0

but it is producing same results or results with incomplete number range after decimal.

Xeshan J
  • 372
  • 5
  • 18
  • 1
    how is `0.00090 - 0.00100` equals `-0001`? it is equal to `-0.0001` which is equal to `-1.00 E-4`. – Blip May 20 '15 at 13:01
  • use `System.out.println(String.format("%.5f", c));` to read answers and you will see what you want. – Blip May 20 '15 at 13:04
  • @Blip what if when it will be like 4-3 then it will produce 1.00000 which is sound not good for me! – Xeshan J May 20 '15 at 16:35

4 Answers4

2

That's how numeric operations are defined in the specification.

Decimal numbers are internally represented as the closest approximation, which in some cases is not the exact literal value.

If you need precise numeric computation, you have to use BigDecimal.

Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40
1

The answers are correct. You might want to read up on how doubles are stored in binary digits. its because it's base 2. If we used something like base 3, then in normal digits, 2/3 would be 0.66666666... but in the "tridigit" it would be 0.2

betarunex
  • 48
  • 1
  • 10
1

The E notation is confusing you (explanation on how it works here)

-1.0000000000000005E-4

is

-0.00010000000000000005

in standard notation and

-8.999999999999999E-5

is

-0.00008999999999999999

in standard notation. All the answer you see are correct (almost, but they are very close, decimal math isn't always precise), just using the E notation.

Community
  • 1
  • 1
J Atkin
  • 3,080
  • 2
  • 19
  • 33
1

try this:

    double  x = 0.00090; 
    double b = 0.00100;

    BigDecimal xd = new BigDecimal(x).setScale(10, RoundingMode.HALF_UP);
    BigDecimal bd = new BigDecimal(b).setScale(10, RoundingMode.HALF_UP);
    BigDecimal cd = xd.multiply(bd);
    double c = cd.doubleValue();

    System.out.println(c);

For precise calculations, like money calculations, you should use BigDecimals, because they have desired precision, and don't lost any accuracy.

If you prefer printing without "E", try this line:

    System.out.println(cd.toPlainString());
Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32