2

I'm trying to do a very basic operation as follows:

double a=21/5;
System.out.println(a);

However, each time I get 4.0 as the output and not 4.2. I'm encountering this for the first time. I've been using Java for years, but never came across this obscurity.

xan
  • 5,125
  • 13
  • 47
  • 80

5 Answers5

8

You are using integer division, which result will always be integer You should use something like this.

double a=(double)21/5;
Arsen Alexanyan
  • 2,975
  • 5
  • 24
  • 42
3

You are doing integer division...

Try:

double a = 21.0/5;
RudolphEst
  • 1,220
  • 13
  • 21
0

Cast the division or specify one of the arguments as a decimal to force the return as a double:

double a = (double)21/5;

-or-

double a = 21.0/5;
ryrich
  • 2,043
  • 14
  • 24
0

Just cast one of the numbers to double:

double a = 21/5.0;
kamituel
  • 32,634
  • 4
  • 77
  • 95
0

Force the cast to double. double a = 21.0/5

This is called Arithmetic promotion. This means that all terms in an equation are made equal to the variable type with the highest precision. In this case double.

christopher
  • 25,939
  • 5
  • 53
  • 88