4 Replies
Latest reply on May 18, 2019 3:09 AM by garrett35  Level 1 (0 points)

Hey there,

how it is (easily!) possible to round a double to 3 decimal numbers in Swift 5?

Example:

let double = 34.53320218

print(double rounded)

Thank you!

• ###### Re: Round Double to 3 decimal numbers  Level 3 (175 points)
```        let double = 34.53320218
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
guard let number =  numberFormatter.string(from: NSNumber(value: double)) else { fatalError("Can not get number") }
print("\(number)") // 34.533
```
• ###### Re: Round Double to 3 decimal numbers  Level 8 (8,115 points)

3 decimal is default value.

To have a different number of decimals, just add

numberFormatter.minimumFractionDigits = 4

numberFormatter.maximumFractionDigits = 4

• ###### Re: Round Double to 3 decimal numbers  Level 8 (5,615 points)

If you want rounding just for showing the result for users, ManuelMB's answer seems to be the best way.

If you want to use the result of roundng for further calculation, you can write something like this:

```let double = 34.53320218
let roundedDouble = round(double*1000)/1000
print(roundedDouble)

```

But please remember, Double represents a binary floating-point number, so it cannot represent decimal `0.001` precisely. The result of calculation using `roundedDouble` can be something you do not expect.

```print(roundedDouble*5) //->172.66500000000002

```

You should better use Decimal, when you want a result based on decimal representation of numbers.