Swift Rounding up Double Swift Rounding up Double swift swift

Swift Rounding up Double


Try:

var numberOfBottles = totalVolume / volumeEachBottlesnumberOfBottles.rounded(.up) 

or

numberOfBottles.rounded(.down)


There is a built-in global function called ceil which does exactly this:

var numberOfBottles = ceil(totalVolume/volumeEachBottles)

This returns 2, as a Double.

enter image description here

ceil is actually declared in math.h and documented here in the OS X man pages. It is almost certainly more efficient than any other approach.

Even if you need an Int as your final result, I would start by calculating ceil like this, and then using the Int constructor on the result of the ceil calculation.


import Foundationvar numberOfBottles = 275.0 / 250.0var rounded = ceil(numberOfBottles)