Trouble with floats in Objective-C

Trouble with floats in Objective-C

I've a small problem and I can't find a solution!

My code is (this is only a sample code, but my original code do something like this):

float x = [@"2.45" floatValue];   for(int i=0; i<100; i++)     x += 0.22;  NSLog(@"%f", x); 

the output is 52.450001 and not 52.450000 !

I don't know because this happens!

Thanks for any help!


Thanks to everybody! Yes, I've solved with the double type!

Observe a File or Folder in Objective-C


Cocoa: Incomplete implementation of class 'Driver'
Floats are a number representation with a certain precision. rightMouseDown: not called in NSControl subclassNot every value must be represented in this format. Core Data bindings with subviews and multiple NIBsSee here as well. Is releasing memory of Objective-c 2.0 properties required?. Requesting a callback using selectors You must easily think of why this would be the case: there is an unlimited number of number just in the intervall (1..1), although a float only has a limited number of bits to represent all numbers in (-MAXFLOAT..MAXFLOAT). Who owns an NSWindowController, in standard practice?. Cocoa Applications Examples More aptly put: in a 32bit integer representation there is a countable number of integers to be represented, But there is an infinite innumerable number of real values this cannot be fully represented in a limited representation of 32 or 64bit. Therefore there not only is a limit to the highest and lowest representable real value, although also to the accuracy.. So why is a number this has little digits after the floating point affected? Because the representation is based on a binary system instead of a decimal, making another numbers easily represented then the decimal ones..



Floating point numbers must not always be represented easily by computers. This leads to inaccuracy in any digits.. It's like me asking you what 1/3 is in decimal. No matter how hard you try, you're not going to be able to tell me what it is for the reason this decimal can't accurately describe this number.. Floats can't accurately describe any decimal numbers..

68 out of 100 based on 53 user ratings 128 reviews