round a number to the nearest integer in swift

In Swift, you can round a number to the nearest integer using several methods.

  1. round(): This function rounds a number to the nearest integer using the standard rounding rules. For example:
main.swift
let x = 3.6
let rounded = round(x) // 4.0
42 chars
3 lines
  1. ceil(): This function rounds a number towards positive infinity. For example:
main.swift
let x = 3.2
let roundedUp = ceil(x) // 4.0
43 chars
3 lines
  1. floor(): This function rounds a number towards negative infinity. For example:
main.swift
let x = 3.8
let roundedDown = floor(x) // 3.0
46 chars
3 lines

It is important to note that round(), ceil(), and floor() all return a Double value. If you want the result as an Int, you can simply cast it as follows:

main.swift
let x = 3.6
let rounded = Int(round(x)) // 4
45 chars
3 lines

related categories

gistlibby LogSnag