152

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?

1

19 Answers 19

190

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
  • 42
    +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
  • 48
    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
  • 20
    No, not rounding: Truncation Jul 2, 2016 at 3:03
  • 4
    @BasilBourque In java terminology, rounding DOWN is towards zero. Rounding FLOOR is towards negative infinity.
    – Andreas
    Dec 31, 2016 at 18:12
32

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;
9

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.

1
  • You can also do this by multiplying with 1.0 if you have variables instead of hard coded numbers. Mar 29, 2023 at 13:45
4

Because you are doing integer division.

As @Noldorin says, if both operators are integers, then integer division is used.

The result 0.33333333 can't be represented as an integer, therefore only the integer part (0) is assigned to the result.

If any of the operators is a double / float, then floating point arithmetic will take place. But you'll have the same problem if you do that:

int n = 1.0 / 3.0;
4

The easiest solution is to just do this

double g = (double) 1 / 3;

What this does, since you didn't enter 1.0 / 3.0, is let you manually convert it to data type double since Java assumed it was Integer division, and it would do it even if it meant narrowing the conversion. This is what is called a cast operator. Here we cast only one operand, and this is enough to avoid integer division (rounding towards zero)

4

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

TL;DR

You can solve it by doing:

double g = 1.0/3.0; 

or

double g = 1.0/3; 

or

double g = 1/3.0; 

or

double g = (double) 1 / 3;

The last of these options is required when you are using variables e.g. int a = 1, b = 3; double g = (double) a / b;.

A more completed answer

double g = 1 / 3;

This result in 0 because

  • first the dividend < divisor;
  • both variables are of type int therefore resulting in int (5.6.2. JLS) which naturally cannot represent the a floating point value such as 0.333333...
  • "Integer division rounds toward 0." 15.17.2 JLS

Why double g = 1.0/3.0; and double g = ((double) 1) / 3; work?

From Chapter 5. Conversions and Promotions one can read:

One conversion context is the operand of a numeric operator such as + or *. The conversion process for such operands is called numeric promotion. Promotion is special in that, in the case of binary operators, the conversion chosen for one operand may depend in part on the type of the other operand expression.

and 5.6.2. Binary Numeric Promotion

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

If either operand is of type double, the other is converted to double.

Otherwise, if either operand is of type float, the other is converted to float.

Otherwise, if either operand is of type long, the other is converted to long.

Otherwise, both operands are converted to type int.

2

you should use

double g=1.0/3;

or

double g=1/3.0;

Integer division returns integer.

2

The conversion in JAVA is quite simple but need some understanding. As explain in the JLS for integer operations:

If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion (§5.6).

And an example is always the best way to translate the JLS ;)

int + long -> long
int(1) + long(2) + int(3) -> long(1+2) + long(3)

Otherwise, the operation is carried out using 32-bit precision, and the result of the numerical operator is of type int. If either operand is not an int, it is first widened to type int by numeric promotion.

short + int -> int + int -> int

A small example using Eclipse to show that even an addition of two shorts will not be that easy :

short s = 1;
s = s + s; <- Compiling error

//possible loss of precision
//  required: short
//  found:    int

This will required a casting with a possible loss of precision.

The same is true for the floating point operators

If at least one of the operands to a numerical operator is of type double, then the operation is carried out using 64-bit floating-point arithmetic, and the result of the numerical operator is a value of type double. If the other operand is not a double, it is first widened (§5.1.5) to type double by numeric promotion (§5.6).

So the promotion is done on the float into double.

And the mix of both integer and floating value result in floating values as said

If at least one of the operands to a binary operator is of floating-point type, then the operation is a floating-point operation, even if the other is integral.

This is true for binary operators but not for "Assignment Operators" like +=

A simple working example is enough to prove this

int i = 1;
i += 1.5f;

The reason is that there is an implicit cast done here, this will be execute like

i = (int) i + 1.5f
i = (int) 2.5f
i = 2
2

I did this.

double g = 1.0/3.0;
System.out.printf("%gf", g);

Use .0 while doing double calculations or else Java will assume you are using Integers. If a Calculation uses any amount of double values, then the output will be a double value. If the are all Integers, then the output will be an Integer.

1

Make the 1 a float and float division will be used

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

1 and 3 are integer contants and so Java does an integer division which's result is 0. If you want to write double constants you have to write 1.0 and 3.0.

0

Because it treats 1 and 3 as integers, therefore rounding the result down to 0, so that it is an integer.

To get the result you are looking for, explicitly tell java that the numbers are doubles like so:

double g = 1.0/3.0;
0

(1/3) means Integer division, thats why you can not get decimal value from this division. To solve this problem use:

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

Since both 1 and 3 are ints the result not rounded but it's truncated. So you ignore fractions and take only wholes.

To avoid this have at least one of your numbers 1 or 3 as a decimal form 1.0 and/or 3.0.

0

I noticed that this is somehow not mentioned in the many replies, but you can also do 1.0 * 1 / 3 to get floating point division. This is more useful when you have variables that you can't just add .0 after it, e.g.

import java.io.*;

public class Main {
    public static void main(String[] args) {
        int x = 10;
        int y = 15;
        System.out.println(1.0 * x / y);
    }
}
-1

Do "double g=1.0/3.0;" instead.

2
  • Just curious...what is wrong with this answer? I used this approach when I first encountered the problem. An explanation of what is wrong with this solution would be appreciated. Thanks in advance. Feb 4, 2018 at 12:04
  • @Mr.PortStJoe It doesn't provide any details to the person asking the question. Looking at the top rated answer, we can see they explained WHY it is happening as well. While the answer may be technically correct, it's usefulness may be seen as limited. Jan 15, 2019 at 22:53
-1

Try this out:

public static void main(String[] args) {
    double a = 1.0;
    double b = 3.0;
    double g = a / b;
    System.out.printf(""+ g);
}
1
  • 1
    Please don't post code-only answers, include an explanation what your code does and how (and why) it solves the problem of the question. Also consider that this is an 8 year old question that has existing upvoted answers, and whether your answer adds any value over the existing answers. Apr 20, 2019 at 10:27
-1

My code was:

System.out.println("enter weight: ");
int weight = myObj.nextInt();

System.out.println("enter height: ");
int height = myObj.nextInt();

double BMI = weight / (height *height)
System.out.println("BMI is: " + BMI);

If user enters weight(Numerator) = 5, and height (Denominator) = 7, BMI is 0 where Denominator > Numerator & it returns interger (5/7 = 0.71 ) so result is 0 ( without decimal values )

Solution :

Option 1:

doubleouble  BMI = (double) weight / ((double)height * (double)height);

Option 2:

double  BMI = (double) weight / (height * height);
-2

Many others have failed to point out the real issue:

An operation on only integers casts the result of the operation to an integer.

This necessarily means that floating point results, that could be displayed as an integer, will be truncated (lop off the decimal part).

What is casting (typecasting / type conversion) you ask?

It varies on the implementation of the language, but Wikipedia has a fairly comprehensive view, and it does talk about coercion as well, which is a pivotal piece of information in answering your question.

http://en.wikipedia.org/wiki/Type_conversion

3
  • This answer is flawed. There is no Type Casting or Type Conversion involved in an all integer devision like 1/2, not in the target language (java). You simply invoke an integer division, which will result in an integer result. The Type Casting is only because of the up-conversion from int to a double during the assignment.
    – YoYo
    Apr 2, 2018 at 15:24
  • @YoYo You're saying 0.5 is an integer? I don't think so, homie.
    – sova
    Apr 3, 2018 at 0:33
  • 2
    this homie didn’t say anything about 0.5. Simply, in Java, 1/2 is an integer division, which results in a zero integer. You can assign a zero to a double, it will still be a zero, albeit a 0.0 double.
    – YoYo
    Apr 3, 2018 at 0:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.