0

I am new to Java and I am using DrJava IDE for my testing. I have the following division 49700/40000 and it displays 1.0 instead of 1.2425.

 double t = 49700/40000;
 System.out.println(t);

Is it something I am doing wrong?

Nair
  • 7,438
  • 10
  • 41
  • 69
  • For reference, similar question and answer. [Division of integers in Java](http://stackoverflow.com/q/7220681/260633) – Dev Sep 01 '13 at 00:30

2 Answers2

5

Try, this instead:

double t = 49700/40000.0;
System.out.println(t);

If both operands are integers the result will be an integer which will be truncated, and then it will be cast in to a double. If, instead, one of the operands is a double, the result will be a double.

Dev
  • 11,919
  • 3
  • 40
  • 53
  • 1
    Excellent, that was my mistake, I should define the source also as double then I get double result back. Thanks for correcting me. – Nair Sep 01 '13 at 00:22
  • 1
    @Nair - You should only define the source as a double if it _IS_ a double. Otherwise you can cast when you divide. – jahroy Sep 01 '13 at 00:53
  • 1
    You can also put a d or f after your numeric constant, e.g. 40000f, but I prefer the trailing .0 as used by @dev. – user949300 Sep 01 '13 at 01:53
0

Use float for decimal number computations

Crickcoder
  • 2,135
  • 4
  • 22
  • 36