views:

178

answers:

3

I am doing a simple :

float x = 151.185436;
printf("x=%f",x);

and the result is

x=151.185440

Whats wrong here? I want to retain and print my original value of 151.185436

Thanks Amarsh

+3  A: 

floats just aren't very accurate. Try double. And read this: http://docs.sun.com/source/806-3568/ncg_goldberg.html

Paul Tomblin
A: 

Floats are inaccurate, use doubles. Also as you're using Objective C and not straight C it might be better if you use Objective C functions for this:

myNumber = [NSNumber numberWithDouble:151.185436];
NSLog(@"myNumber = %@", myNumber);
pheelicks
Both floats and doubles are "inaccurate" - it's just a question of degree.
Paul R
+2  A: 

A float can only hold 32 bits (4 bytes) of information about your number - it can't just store as many decimal places as you need it to. 151.18544 is as close to your value that the float could represent without running out of bits.

For the precision you want, you need to use a double instead of a float.

Mike Howard