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]];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With