NSNumber from CGFloat
13,161
Solution 1
I believe @
NSNumber
literal is good enough
@(myCGFloat)
Read more here: http://clang.llvm.org/docs/ObjectiveCLiterals.html
Solution 2
This is how I handled it:
@interface NSNumber (CGFloatAdditions)
+ (NSNumber*)numberWithCGFloat: (CGFloat)value;
- (CGFloat)CGFloatValue;
@end
@implementation NSNumber (CGFloatAdditions)
+ (NSNumber*)numberWithCGFloat: (CGFloat)value
{
#if CGFLOAT_IS_DOUBLE
return [NSNumber numberWithDouble: (double)value];
#else
return [NSNumber numberWithFloat: value];
#endif
}
- (CGFloat)CGFloatValue
{
#if CGFLOAT_IS_DOUBLE
return [self doubleValue];
#else
return [self floatValue];
#endif
}
@end
CGFLOAT_IS_DOUBLE
is defined in CGBase.h
conditionally by platform.
Author by
Guillaume Algis
Updated on June 04, 2022Comments
-
Guillaume Algis almost 2 years
Is there a safe way to "convert" a
CGFloat
to aNSNumber
?NSNumber
has thenumberWithFloat:
andnumberWithDouble:
methods butCGFloat
being defined asfloat
ordouble
depending on the platform, it seems risky to use either one of them.Or is
numberWithDouble:
safe to use with aCGFloat
, as it is the one with the more precision ?