Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why (int)(14/13 - 0.001) yield 0 and not 1?

Isn't it true that if you cast a float number like 1.0012 to an integer, it will become 1?

Then why is it when I write:

(int)(14/13-0.001) 

instead of 1.07592 ~ become 1 it becomes 0 ?

(Java compiled with Eclipse).

like image 689
Ricky Leo Saputra Avatar asked Mar 02 '14 08:03

Ricky Leo Saputra


2 Answers

It does truncating. For 1.0012 it just removes part on right of decimal point.

In example

(int)(14/13-0.001)

14/13 will be 1 and then it will be converted to double, 1.0-0.001 = 0.999, and after truncating it becomes 0.

like image 140
Dejan Avatar answered Nov 14 '22 11:11

Dejan


14 / 13 is an integer division. Its value is 1.

1 - 0.01 is thus lower than 1.

Casting it to int thus yields 0.

Use 14.0 / 13 - 0.001 or 14d / 13 - 0.001 instead.

like image 8
JB Nizet Avatar answered Nov 14 '22 13:11

JB Nizet