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

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

    This is a sort of a long workaround, which may come in handy if your needs are a little more complex. You can use a number formatter in Swift.

    let numberFormatter: NSNumberFormatter = {
        let nf = NSNumberFormatter()
        nf.numberStyle = .DecimalStyle
        nf.minimumFractionDigits = 0
        nf.maximumFractionDigits = 1
        return nf
    }()
    

    Suppose your variable you want to print is

    var printVar = 3.567
    

    This will make sure it is returned in the desired format:

    numberFormatter.StringFromNumber(printVar)
    

    The result here will thus be "3.6" (rounded). While this is not the most economic solution, I give it because the OP mentioned printing (in which case a String is not undesirable), and because this class allows for multiple parameters to be set.

提交回复
热议问题