Site icon Nabtron

Rounding Double in Swift

Rounding a Double in swift is quite simple and easy (tested up to swift 5.1).

We simply need to use the round() function provided by swift. The example below will demonstrate how to use this function effectively, while keeping your number still a Double (without changing the type).

This example has been tested in xcode 8.2 using swift 3.0.1 on Macbook pro running macOS Sierra.

How to round Double to 2 decimal places in Swift 3.0 to 5.1

Imagine that we have this code:

var a = 1.999999999

We might have acquired this variable dynamically too though.

Now we want to round its value to 2 decimal places, we can achieve this by:

round(100*a)/100

What we have done here is that we used the round function. Then inside that function we simply multiplied our variable with 100. In the end we simply divided the whole round function output by 100, to bring back the value to the same one before we started (100/100 = 1).

Tip: We need to add as many zeros to 1 while multiplying and dividing, as many digits we want after the decimal point in our Double.

E.g. if we need 3 digits after the decimal point, then we will multiply and divide by 1000.

The complete code of above example (for 2 digits after the decimal) will become:

import UIKit

var a = 1.777777

a = round(100*a)/100

Importing UIKit is important as round function is part of it.

There’s another method to limit a Float to certain digits after the decimal point too. However that method results in type conversion of the new variable to string (not of the original one though). We might need to type cast the new variable back to Float or Double if we intent to use it further in any scenario which requires it to be of specific type.

The code for float to string with specific digits after decimals is:

var b = 1.777777

var roundedString = String(format: "%.2f", b)

Here the %.2f tells the swift to make this number rounded to 2 decimal places.

Exit mobile version