How to truncate decimals to x places in Swift

owlswipe picture owlswipe · Mar 11, 2016 · Viewed 18.6k times · Source

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

Help is appreciated!

Note: This is not a duplicate because they are using a very old version of swift, before some of these functions were made. Also, they are using floats and integers, whereas I am talking about doubles. And their question/answers are much more complicated.

Answer

Russell picture Russell · Mar 11, 2016

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