How to truncate decimals to x places in Swift How to truncate decimals to x places in Swift ios ios

How to truncate decimals to x places in Swift


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 placesprint(num.truncate(places: 2))// return the number truncated to 6 placesprint(num.truncate(places: 6))


I figured this one out.

Just floor (round down) the number, with some fancy tricks.

let x = 1.23556789let y = Double(floor(10000*x)/10000) // leaves on first four decimal placeslet z = Double(floor(1000*x)/1000) // leaves on first three decimal placesprint(y) // 1.2355print(z) // 1.235

So, multiply by 1 and the number of 0s being the decimal places you want, floor that, and divide it by what you multiplied it by. And voila.


You can keep it simple with:

String(format: "%.0f", ratio*100)

Where 0 is the amount of decimals you want to allow. In this case zero. Ratio is a double like: 0.5556633.Hope it helps.