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:
However, if you want to round decimal numbers to a fixed number of decimal places, you may find the following function handy:
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:
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.