Rounding a double value to x number of decimal places in swift

前端 未结 28 3071
日久生厌
日久生厌 2020-11-22 06:11

Can anyone tell me how to round a double value to x number of decimal places in Swift?

I have:

var totalWorkTimeInHours = (totalWorkTime/60/60)
         


        
28条回答
  •  日久生厌
    2020-11-22 06:46

    Either:

    1. Using String(format:):

      • Typecast Double to String with %.3f format specifier and then back to Double

        Double(String(format: "%.3f", 10.123546789))!
        
      • Or extend Double to handle N-Decimal places:

        extension Double {
            func rounded(toDecimalPlaces n: Int) -> Double {
                return Double(String(format: "%.\(n)f", self))!
            }
        }
        
    2. By calculation

      • multiply with 10^3, round it and then divide by 10^3...

        (1000 * 10.123546789).rounded()/1000
        
      • Or extend Double to handle N-Decimal places:

        extension Double {    
            func rounded(toDecimalPlaces n: Int) -> Double {
                let multiplier = pow(10, Double(n))
                return (multiplier * self).rounded()/multiplier
            }
        }
        

提交回复
热议问题