Rounding in Swift with round() Rounding in Swift with round() swift swift

Rounding in Swift with round()


You can do:

round(1000 * x) / 1000


Updated answer

The round(someDecimal) is the old C style. As of Swift 3, doubles and floats have a built in Swift function.

var x = 0.8x.round() // x is 1.0 (rounds x in place)

or

var x = 0.8var y = x.rounded() // y is 1.0, x is 0.8

See my answer fuller answer here (or here) for more details about how different rounding rules can be used.

As other answers have noted, if you want to round to the thousandth, then multiply temporarily by 1000 before you round.


func round(value: Float, decimalPlaces: UInt) {  decimalValue = pow(10, decimalPlaces)  round(value * decimalValue) / decimalValue}func round(value: CGFloat, decimalPlaces: UInt)func round(value: Double, decimalPlaces: UInt)func roundf(value: Float, decimalPlaces: UInt)