6

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).

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
  • 6
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – phuclv Mar 02 '14 at 08:51
  • 2
    the title of question is not correct, `(int)(1.01 - 0.01)` will produce 1 not 0. – sakura Mar 02 '14 at 08:55
  • 14/13 is equal to 1 if they are integers - and they are in your example. Subtracting .01 and then taking the it will produce 0 – Rob Mar 02 '14 at 08:55
  • 1
    [is floating point math broken](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Lutz Lehmann Mar 02 '14 at 08:56
  • In primary school you might have done integer division where something like `14 divided by` 13 is `1 with 1 remainder`. This is how integer arithmetic works and you can do `14 % 13` to get the remainder. – Peter Lawrey Mar 02 '14 at 09:06
  • 3
    @LưuVĩnhPhúc Thanks for your suggestion, but if you actually take the time to read the question, you will see that the OP is not at the stage where the document you provide a link to is likely to help. – Pascal Cuoq Mar 02 '14 at 17:51
  • @PascalCuoq sorry I was not reading carefully at first – phuclv Mar 02 '14 at 23:53

2 Answers2

12

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.

Dejan
  • 3,046
  • 3
  • 28
  • 43
8

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.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255