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

        Hey there,


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


        let double = 34.53320218

        print(double rounded)


        Thank you!

        • Re: Round Double to 3 decimal numbers
          ManuelMB Level 3 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
            OOPer Level 7 Level 7 (4,945 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


            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.