Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does conversion from double to int work in Java?

For the following code (Java):

double d = (double) m / n; //m and n are integers, n>0
int i = (int) (d * n);

i == m

Is the last expression always true? If it's not is this always true?:

i = (int) Math.round(d * n);

i == m
like image 915
zduny Avatar asked Aug 10 '11 17:08

zduny


1 Answers

int i = (int) (d * n); i == m;

This is false for m=1, n=49.

i = (int) Math.round(d * n); i == m;

My intuition tells me it should be true, but it may be hard to prove rigorously.

like image 163
Nayuki Avatar answered Oct 26 '22 23:10

Nayuki