Reputation: 55544
A user inputs a number (either a float or integer), and it must be greater than a lower bound.
This is the code to get the number from the UITextField:
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *currentNumber = [f numberFromString:self.textfield.text];
[f release];
The lower bound is often 0.1 (lowerBound
is an NSNumber)
If I have this code and I enter 0.1 into the textfield, then isValid
remains YES
.
BOOL isValid = YES;
if ([currentNumber floatValue] < [self.lowerBound floatValue]) {
isValid = NO;
}
However I though it would be better to do:
BOOL isValid = YES;
if ([currentNumber compare:self.lowerBound] == NSOrderedAscending) {
isValid = NO;
}
However I enter 0.1 again (and the lowerBound is still 0.1) the if statement evaluates to true (as if currentNumber is less than self.lowerBound).
The code works as expected for 0.11 and above. I also have a higher bound:
BOOL isValid = YES;
if ([currentNumber compare:self.higherBound] == NSOrderDescending) {
isValid = NO;
}
And this works as expected, including when I enter the same value as the higherBound (10 in most cases)
As I understand it the compare:
method on NSNumber compares the values and not the addresses of the objects, so why doesn't it work on the lower bound?
Upvotes: 2
Views: 350
Reputation:
Because floating point numbers are not exact - the 0.1 in the one NSNumber may be different from the one in the other NSNumber.
Upvotes: 2