Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 493
owlswipe Avatar asked Mar 11 '16 17:03

owlswipe


People also ask

How do I truncate decimal places?

To truncate a number to 1 decimal place, miss off all the digits after the first decimal place. To truncate a number to 2 decimal places, miss off all the digits after the second decimal place.

How do I get only 2 decimal places in Swift?

The "%f" format string means "a floating point number," but "%. 2f" means "a floating-point number with two digits after the decimal point. When you use this initializer, Swift will automatically round the final digit as needed based on the following number.

How do you truncate a number in Swift?

Here, we are going to learn how to truncate a double number in Swift programming language? Problem Solution: Here, we will truncate a double number using the trunc() function. The trunc() function accepts a double number and returns the truncated number to the calling function.

How do I limit the number of decimal places?

Now you can limit the decimal places. Select the number cell and in the Menu, go to Format > Number > More Formats > Custom number format.


2 Answers

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))
like image 81
Russell Avatar answered Oct 16 '22 22:10

Russell


I figured this one out.

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

let x = 1.23556789
let y = Double(floor(10000*x)/10000) // leaves on first four decimal places
let z = Double(floor(1000*x)/1000) // leaves on first three decimal places
print(y) // 1.2355
print(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.

like image 39
owlswipe Avatar answered Oct 16 '22 22:10

owlswipe