What is the best way of checking if a NSNumber
is a fraction?
NumberIsFraction(@(0)); // NO;
NumberIsFraction(@(0.5)); // YES;
NumberIsFraction(@(1.0)); // NO;
"Best" in terms of border case handling and performance.
What is the best way of checking if a NSNumber
is a fraction?
NumberIsFraction(@(0)); // NO;
NumberIsFraction(@(0.5)); // YES;
NumberIsFraction(@(1.0)); // NO;
"Best" in terms of border case handling and performance.
Avoiding conversions to types with a smaller domain:
BOOL NumberIsFraction(NSNumber *number) {
double dValue = [number doubleValue];
if (dValue < 0.0)
return (dValue != ceil(dValue));
else
return (dValue != floor(dValue));
}
The solutions from Jonathan, hpique, and prashant all have the same bug: they involve casting NSNumber
to fixed-precision types (variously double
, long long
, etc.), which breaks if the value is a very large NSDecimalNumber
. For example, the accepted answer fails on NSDecimalNumber(string: "1000000000000000.1")
.
A more correct implementation (as an extension, in Swift):
extension NSNumber {
var isFraction: Bool {
var decimal = decimalValue, decimalRounded = decimal
NSDecimalRound(&decimalRounded, &decimal, 0, .down)
return NSDecimalNumber(decimal: decimalRounded) != self
}
}
Or in Objective-C, as a global function:
BOOL NumberIsFraction(NSNumber *number) {
NSDecimal rounded = number.decimalValue;
NSDecimalRound(&rounded, &rounded, 0, NSRoundDown);
return ![number isEqualToNumber:
[[NSDecimalNumber alloc] initWithDecimal:rounded]];
}
I'm currently using:
BOOL NumberIsFraction(NSNumber* number) {
return ![number isEqualToNumber:@(number.longLongValue)];
}
long long
. –
Amhara -(BOOL) NumberIsFraction: (NSNumber*)number
{
NSLog(@"%0.16g",number.doubleValue);
NSLog(@"%d", number.intValue);
double diff = number.doubleValue - number.intValue;
if (diff>0)
return YES;
else return NO;
}
© 2022 - 2024 — McMap. All rights reserved.
!=
?NumberIsFraction(@(0.0f))
would returnYES
, wouldn't it? – Tripping