-1

When doing the following in Java, i get as the result 0.0. Even though the result should be 10. This is an example calculation, in my code it's doing this with with double values.

double result = (10 / 100) * 100;
Wesley Egbertsen
  • 720
  • 1
  • 8
  • 25
  • 5
    Because `10 / 100 = 0`. – Tunaki Sep 17 '15 at 12:46
  • 5
    @WesleyEgbertsen: No, it doesn't. Not when you're doing integer arithmetic, which is what happens when both operands of `/` are `int`. – Jon Skeet Sep 17 '15 at 12:49
  • 1
    I lot of people are using [that question](http://stackoverflow.com/questions/3144610/java-integer-division-how-do-you-produce-a-double) as a close-target (here and on several other questions). Frankly, it seems like a really poor one. [This](http://stackoverflow.com/questions/7286681/why-does-my-java-division-code-give-the-wrong-answer) is a bit better. – T.J. Crowder Sep 17 '15 at 12:51

3 Answers3

7

10 and 100 are integer literals, so 10 / 100 is evaluated in integer arithmetic which means that any remainder is discarded.

So you get (10 / 100) * 100 = (0) * 100

One fix is to promote one of the arguments to a double:

(10.0 / 100) * 100

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

Try this:

double result = (10.0 / 100) * 100
jchamp
  • 172
  • 3
  • 11
0

You are working with integer and int 10 / int 100 is 0. 0 * 100 is also 0

Andriel
  • 26
  • 4