Search code examples
iosswiftdoubledecimal

How to truncate decimals to x places in Swift


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 output to be 17.9384). I do not want to round the number to 17.9385.

How can I do this?


Solution

  • 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)))
        }
    }
    

    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))