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?
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.
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.
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.
Now you can limit the decimal places. Select the number cell and in the Menu, go to Format > Number > More Formats > Custom number format.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With