Luis Gustavo Origa
Luis Gustavo Origa

Reputation: 383

Swift Rounding up Double

I am trying to round a double up to a whole number,

var numberOfBottles = totalVolume / volumeEachBottles

for example numberOfBottles = 275.0 / 250.0 that would give me 1.1, I need it to round up to 2

Upvotes: 39

Views: 26920

Answers (4)

Patrik Rikama-Hinnenberg
Patrik Rikama-Hinnenberg

Reputation: 1620

In case you are looking for rounding it to a whole number and use it in the UI then this can be useful. Just add this as the last thing in your file or in a own file:

extension Double {
func roundToInt() -> Int{
    return Int(Darwin.round(self))
}

}

And use it like this if you like to have it in a textlabel:

currentTemp.text = "\(weatherData.tempCelsius.roundToInt())"

Or print it as an Int:

print(weatherData.tempCelsius.roundToInt())

Upvotes: 0

DouglasHeitner
DouglasHeitner

Reputation: 67

import Foundation

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

Upvotes: 1

João Nunes
João Nunes

Reputation: 3761

Try:

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

or

numberOfBottles.rounded(.down)

Upvotes: 65

nhgrif
nhgrif

Reputation: 62072

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.

Upvotes: 24

Related Questions