Rounding Functions

Swift contains four built-in founding functions:

  • round – Rounds up from 0.5 and higher and rounds down from 0.49 and lower
  • floor – Rounds to the lowest integer
  • ceil – Rounds to the highest integer
  • trunc – Drops the decimal value

To see how these different rounding function is work, just copy this Swift code into a Swift playground so you can see them in action:

import Cocoa

var testNumber : Double

testNumber = round(36.98)
testNumber = round(-36.98)
testNumber = round(36.08)

testNumber = floor(36.98)
testNumber = floor(-36.98)
testNumber = floor(36.08)

testNumber = ceil(36.98)
testNumber = ceil(-36.98)
testNumber = ceil(36.08)

testNumber = trunc(36.98)
testNumber = trunc(-36.98)
testNumber = trunc(36.08)

However, if you want to round decimal numbers to a fixed number of decimal places, you may find the following function handy:

func roundToPlaces(value: Double, decimalPlaces: Int) -> Double {
    let divisor = pow(10.0, Double(decimalPlaces))
    return round(value * divisor) / divisor
}

To use this function, you just need to define the number you want to round and the number of decimal places to display such as:

import Cocoa

var number = 23.45
var number2 = 1.29
var total : Double

func roundToPlaces(value: Double, decimalPlaces: Int) -> Double {
    let divisor = pow(10.0, Double(decimalPlaces))
    return round(value * divisor) / divisor
}


total = roundToPlaces(value: number / number2, decimalPlaces: 3)

This Swift code would display three decimal places such as 18.178. Any time you need to round numbers to specific decimal places, add the roundToPlaces function to your own code.

To learn more about different rounding functions, click here.

 

December 16th, 2016 by
HTML Snippets Powered By : XYZScripts.com