Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with division using double type in Java

Okay. I have been bashing my head against the wall for like 2 hours now trying to figure out why in the world double answer = 364/365; is telling me that answer is 0. Or any other combination of double for that matter, its just truncating the decimal and I just don't know why.

like image 816
Jeff Avatar asked Feb 16 '10 05:02

Jeff


People also ask

Can you divide double in Java?

When one of the operands to a division is a double and the other is an int, Java implicitly (i.e. behind your back) casts the int operand to a double. Thus, Java performs the real division 7.0 / 3.0.

What is the datatype for division in Java?

In java, operations involving only integer types (int, long and so on) have integer results. This includes divisions. Both 30 and 4 are integer values, so if you try to divide them, integer division is used.


2 Answers

364/365 performs integer division (truncates the decimal).

Try double answer = 364.0/365; to force it to perform floating point division.

Something like:

double days_in_year = 365;
double answer = 364/days_in_year;

would work as well, since one of the operands isn't an integer.

like image 118
Sapph Avatar answered Sep 30 '22 03:09

Sapph


You're taking an int type (364) and dividing by another int type (365) - the answer is going to be an int. This is then stored in a double type answer. You could do the following:

double answer = 364d / 365d;

More info here:

http://mindprod.com/jgloss/division.html

like image 41
Jon Avatar answered Sep 30 '22 05:09

Jon