Categories
integer-division java

Int division: Why is the result of 1/3 == 0?

137

I was writing this code:

public static void main(String[] args) {
    double g = 1 / 3;
    System.out.printf("%.2f", g);
}

The result is 0. Why is this, and how do I solve this problem?

0

    176

    The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division.

    Integer division of course returns the true result of division rounded towards zero. The result of 0.333... is thus rounded down to 0 here. (Note that the processor doesn’t actually do any rounding, but you can think of it that way still.)

    Also, note that if both operands (numbers) are given as floats; 3.0 and 1.0, or even just the first, then floating-point arithmetic is used, giving you 0.333....

    6

    • 37

      +1 and it always rounds down. int i = .99999999 sets int to 0. More specifically, it takes the integer portion and discards the rest.

      Jan 13, 2011 at 21:30


    • 42

      It rounds “towards zero” which is “downwards” for values greater than zero. (+0.9 gets rounded to 0, -0.9 also gets rounded to 0.)

      Jan 13, 2011 at 21:32

    • @Byron: Yep, exactly. I don’t believe the processor actually does any rounding, since division is implemented very differently, but it’s handy to think of it that way.

      – Noldorin

      Jan 13, 2011 at 21:32


    • 18

      No, not rounding: Truncation

      Jul 2, 2016 at 3:03


    • 3

      @BasilBourque In java terminology, rounding DOWN is towards zero. Rounding FLOOR is towards negative infinity.

      – Andreas

      Dec 31, 2016 at 18:12

    30

    1/3 uses integer division as both sides are integers.

    You need at least one of them to be float or double.

    If you are entering the values in the source code like your question, you can do 1.0/3 ; the 1.0 is a double.

    If you get the values from elsewhere you can use (double) to turn the int into a double.

    int x = ...;
    int y = ...;
    double value = ((double) x) / y;
    

      10

      Explicitly cast it as a double

      double g = 1.0/3.0
      

      This happens because Java uses the integer division operation for 1 and 3 since you entered them as integer constants.

      0