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

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

    The best way to format a double property is to use the Apple predefined methods.

    mutating func round(_ rule: FloatingPointRoundingRule)
    

    FloatingPointRoundingRule is a enum which has following possibilities

    Enumeration Cases:

    case awayFromZero Round to the closest allowed value whose magnitude is greater than or equal to that of the source.

    case down Round to the closest allowed value that is less than or equal to the source.

    case toNearestOrAwayFromZero Round to the closest allowed value; if two values are equally close, the one with greater magnitude is chosen.

    case toNearestOrEven Round to the closest allowed value; if two values are equally close, the even one is chosen.

    case towardZero Round to the closest allowed value whose magnitude is less than or equal to that of the source.

    case up Round to the closest allowed value that is greater than or equal to the source.

    var aNumber : Double = 5.2
    aNumber.rounded(.up) // 6.0
    

提交回复
热议问题