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!
- Retain cycle in completion block
- OSX application without storyboard or xib files using Swift
- How do I run a Cocoa app after building it from the command line with xcodebuild?
- If “a == b” is false when comparing two NSString objects
- Better way of incrementing build number?
- Rounding numbers in Objective-C
3 Solutions Collect From Internet About “Trouble with floats in Objective-C”
Floats are a number representation with a certain precision. Not every value can be represented in this format. See here as well.
You can easily think of why this would be the case: there is an unlimited number of number just in the intervall (1..1), but a float only has a limited number of bits to represent all numbers in (-MAXFLOAT..MAXFLOAT).
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 that 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, but also to the accuracy.
So why is a number that has little digits after the floating point affected? Because the representation is based on a binary system instead of a decimal, making other numbers easily represented then the decimal ones.
Floating point numbers can not always be represented easily by computers. This leads to inaccuracy in some 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 because decimal can’t accurately describe that number.
Floats can’t accurately describe some decimal numbers.
- UICollectionVIew: Animate cells as they scroll in
- distanceFromLocation – Calculate distance between two points
- (Swift) how to print “\” character in a string?
- NSXMLParser problem with “&”(Ampersand) character
- Add subview with UIAlertVIew like animation,with a bouncing effect
- GameCenter Leaderboard will not update after release
- how do I rotate a group of buttons programmatically in Swift?
- Remote notification method called twice
- Node group's position is reset at the start of SCNNode.runAction
- Black Bar in UIImagePicker on iPad – Only in Landscape Right Orientation
- SecPKCS12Import does not return any items
- Reset iOS Simulator application data to run app for first time
- Image on UIbutton visible on simulator but lost on device
- Links don't open in external browser in JQuery Mobile with PhoneGap
- How do I decode HTML entities in swift?