Round Double to 3 decimal numbers

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!

  • This accepted answer does not help if I need to do math with the resulting value.

    Try this: 5.02 * .06 where 5.02 is the cost of the product and .06 is the sales tax rate. Once you move the NSNumber to a Double or Float the cost value becomes 5.0199999... and don't trust Playground examples. They show the .round and *100 /100 tricks working but in compiled Swift they don't!

    I am going through a nightmare of code to write a reliable rounding a Double to 2 decimal positions so I can do a calculation!

  • @sykste        Doesn't      let res = round(100 * 5.02 * 0.06)/100    make it ? To get 2 decimals, format string:           label.text = String(format: "%.2f", res)         Tested in code as well as playground.  What do you expect ?

  • @sykste, as I wrote, binary floating point number like Double cannot represent values like 5.02 nor .06 precisely. You may need to use Decimal or find a more suitable way of rounding for your purpose. Better start your own thread with detailed description (including your code) showing your purpose.

Add a Comment

Accepted Reply

        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

Replies

        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

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.

  • Even after 4 years of using Swift daily, I had never seen Decimal. Thank you 🙏🏻

Add a Comment

3 decimal is default value.


To have a different number of decimals, just add

numberFormatter.minimumFractionDigits = 4

numberFormatter.maximumFractionDigits = 4

Thank you all!