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

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

提交回复
热议问题