3

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
  • 4,640
  • 13
  • 50
  • 83

5 Answers5

10

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

double a=(double)21/5;
Arsen Alexanyan
  • 3,061
  • 5
  • 25
  • 45
3

You are doing integer division...

Try:

double a = 21.0/5;
RudolphEst
  • 1,240
  • 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,164
  • 16
  • 24
0

Just cast one of the numbers to double:

double a = 21/5.0;
kamituel
  • 34,606
  • 6
  • 81
  • 98
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
  • 26,815
  • 5
  • 55
  • 89