How can I round up a CGFloat in Swift?
I've tried ceil(CDouble(myCGFloat))
but that only works on iPad Air & iPhone 5S.
When running on another simulated device I get an error saying 'NSNumber' is not a subtype of 'CGFloat'
How can I round up a CGFloat in Swift?
I've tried ceil(CDouble(myCGFloat))
but that only works on iPad Air & iPhone 5S.
When running on another simulated device I get an error saying 'NSNumber' is not a subtype of 'CGFloat'
With Swift 3, according to your needs, you may choose one of the 4 following ways to round up a
CGFloat
.#1. Using
FloatingPoint
protocolrounded(_:)
methodFloatingPoint
protocol gives types that conform to it arounded(_:)
method.rounded(_:)
has the following declaration:The Playground code below shows how to use
rounded(_:)
in order to round up aCGFloat
value:#2. Using
ceil(_:)
functionDarwin provides a
ceil(_:)
function that has the following declaration:The Playground code below shows how to use
ceil(_:)
in order to round up aCGFloat
value:#3. Using
NSDecimalNumber
NSDecimalNumber
offers a verbose but powerful solution for rounding numbers.#4. Using
NumberFormatter
If you want to round up a
CGFloat
and format it with style in the same operation, you may useNumberFormatter
.The most correct syntax would probably be:
To use
ceil
I will first make theCGFloat
aDouble
and after ceiling, I convert it back toCGFloat
.That works when
CGFloat
is defined either asCFloat
orCDouble
.You could also define a
ceil
for floats (This has been actually implemented in Swift 2):Then you will be able to call directly
while preserving type safety.
I actually believe this should be the solution chosen by Apple, instead of having separate
ceil
andceilf
functions because they don't make sense in Swift.Building off of holex's answer. I did
-edit extension edition-
I also recently turned this into an extension for Floats thought I'd share as well :)
This is makes it so you can just be like
Update: Apple have now defined some CGFloat-specific versions of common functions like
ceil
:...specifically to cope with the 32/64-bit difference. If you simply use
ceil
with a CGFloat argument it should now work on all architectures.My original answer:
This is pretty horrible, I think, but can anyone think of a better way?
#if
doesn't seem to work forCGFLOAT_IS_DOUBLE
; I think you're limited to build configurations, from what I can see in the documentation for conditional compilation.from Swift Standard Library you can round it in-place as well: