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.
The code for specific digits after decimals is:
And ultimately, your number gets truncate without round...
You can tidy this up even more, by making it an extension of
Double
and you use it like this
I figured this one out.
Just floor (round down) the number, with some fancy tricks.
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.
Drag/Drop Solution, IOS, Swift 4
Copy this code into your application...
Then you can call this function like:
Will produce the following: