How to truncate decimals to x places in Swift

前端 未结 9 1957
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:09

    Drag/Drop Solution, IOS, Swift 4

    Copy this code into your application...

    import Foundation
    
    func truncateDigitsAfterDecimal(number: Double, afterDecimalDigits: Int) -> Double {
       if afterDecimalDigits < 1 || afterDecimalDigits > 512 {return 0.0}
       return Double(String(format: "%.\(afterDecimalDigits)f", number))!
    }
    

    Then you can call this function like:

    truncateDigitsAfterDecimal(number: 45.123456789, afterDecimalDigits: 3)
    

    Will produce the following:

    45.123
    

提交回复
热议问题