How to truncate decimals to x places in Swift

前端 未结 9 1928
Happy的楠姐
Happy的楠姐 2020-12-04 01:26

In my swift program, I have a really long decimal number (say 17.9384693864596069567) and I want to truncate the decimal to a few decimal places (so I want the

9条回答
  •  温柔的废话
    2020-12-04 02:18

    You can tidy this up even more, by making it an extension of Double

    extension Double
    {
        func truncate(places : Int)-> Double
        {
            return Double(floor(pow(10.0, Double(places)) * self)/pow(10.0, Double(places)))
        }
    }
    

    and you use it like this

    var num = 1.23456789
    // return the number truncated to 2 places
    print(num.truncate(places: 2))
    
    // return the number truncated to 6 places
    print(num.truncate(places: 6))
    

提交回复
热议问题