While playing around, I found the round() function in swift. It can be used as below:
round(0.8)
Which will return 1, as expected. Here's my question:
how do I round by thousandths in swift?
I want to be able to plug in a number, say 0.6849, and get 0.685 back. How does round() do this? Or, does it not, in which case, what function does?
You can do:
This will round to any value not limited by powers of 10.
Here's one way to do it. You could easily do this for
Float
, or probably make it generic so it's for any of those.Swift 3
The
round(someDecimal)
is the old C style. Doubles and floats have a built in Swift function now.or
See my answer fuller answer here (or here) for more details about how different rounding rules can be used.
As other answers have noted, if you want to round to the thousandth, then multiply temporarily by
1000
before you round.Swift 4: