I am probably missing something obvious (still learning about Objective-C!) but for some reason one of my NSString variables has a null value in my if statement and I don’t know why?
I have even output to NSLog and I still can’t see why it’s behaving like this.
Basically, the user enters an amount in a text field (itemWeight) and this if statement validates the input and displays an alert according to the result. The problem only seems to be when 0.751 is entered, if you enter any other amount (0.750, 0.749, 0.752, 0.753 and so on) it works as expected.
Relevant code samples as follows…
.h file:
@property (strong, nonatomic) IBOutlet UITextField *itemWeight;
.m file:
NSString *rawWeightText = itemWeight.text;
float convertedWeightText = rawWeightText.floatValue;
NSString *weightMessage;
if (convertedWeightText <= 0.750)
{
weightMessage = @"under 0.750";
}
else if (convertedWeightText >= 0.751)
{
weightMessage = @"0.751 or over";
}
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: @"Error"
message: weightMessage
delegate: nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
Any ideas where I’m going wrong/what I’ve forgotten to do would be much appreciated, thank you!
Looking at the condition of your if-else if code does not have the range of from
0.750 to 0.751.floating-point values must be careful to compare. you should consider about
0.751possibility0.75099999...the following loop, the result is 99.999046, not 100. Continue to add more accuracy is poor.
So, In General, Comparison of these expressions is not recommended.
Writing the following method is recommended to compare.
For more information, please read here
http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
also, you must read this wiki:
http://en.wikipedia.org/wiki/Floating_point
http://en.wikipedia.org/wiki/Denormal_number