float abc = 145606035;
NSLog(@"%f", abc);
NSLog(@"%d", abc);
First NSLog = 145606032.000000 //this is wrong, please look at the last digit.
Second NSLog = 536870912 //this is wrong too!
Why the answer so weird? Does it make sense? The ‘abc’ not even exceed the Integer maximum number, how come the number is wrong? Anyway to fix this?
The reason is because it interprets the binary representation of abc as an integer. Decimal numbers and integers in binary representation are completely different and to get the correct output you should cast abc to an int
(int)abcThe first output is off because of the precision of floating point numbers. A float has to break it’s precision into the whole part of the number as well as sign and trailing decimals. This means that the range for floating point numbers is limited especially using 32 bit floats. With double type you should get the correct output for the first number.