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

前端 未结 28 2537
日久生厌
日久生厌 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:43

    To avoid Float imperfections use Decimal

    extension Float {
        func rounded(rule: NSDecimalNumber.RoundingMode, scale: Int) -> Float {
            var result: Decimal = 0
            var decimalSelf = NSNumber(value: self).decimalValue
            NSDecimalRound(&result, &decimalSelf, scale, rule)
            return (result as NSNumber).floatValue
        }
    }
    

    ex.
    1075.58 rounds to 1075.57 when using Float with scale: 2 and .down
    1075.58 rounds to 1075.58 when using Decimal with scale: 2 and .down

    0 讨论(0)
  • 2020-11-22 06:44

    The code for specific digits after decimals is:

    var a = 1.543240952039
    var roundedString = String(format: "%.3f", a)
    

    Here the %.3f tells the swift to make this number rounded to 3 decimal places.and if you want double number, you may use this code:

    // String to Double

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

    0 讨论(0)
  • 2020-11-22 06:44

    Here's one for SwiftUI if you need a Text element with the number value.

    struct RoundedDigitText : View {
        let digits : Int
        let number : Double
    
        var body : some View {
            Text(String(format: "%.\(digits)f", number))
        }
    }
    
    0 讨论(0)
  • 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
            }
        }
        
    0 讨论(0)
  • 2020-11-22 06:46
    extension String{
      var roundedValue:String {
         return String(format: "%.3f", self)
    }}
    

    Usage :

    totalWorkTimeInHours.roundedValue
    
    0 讨论(0)
  • 2020-11-22 06:48

    Extension for Swift 2

    A more general solution is the following extension, which works with Swift 2 & iOS 9:

    extension Double {
        /// Rounds the double to decimal places value
        func roundToPlaces(places:Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return round(self * divisor) / divisor
        }
    }
    


    Extension for Swift 3

    In Swift 3 round is replaced by rounded:

    extension Double {
        /// Rounds the double to decimal places value
        func rounded(toPlaces places:Int) -> Double {
            let divisor = pow(10.0, Double(places))
            return (self * divisor).rounded() / divisor
        }
    }
    


    Example which returns Double rounded to 4 decimal places:

    let x = Double(0.123456789).roundToPlaces(4)  // x becomes 0.1235 under Swift 2
    let x = Double(0.123456789).rounded(toPlaces: 4)  // Swift 3 version
    
    0 讨论(0)
提交回复
热议问题