Can anyone tell me how to round a double value to x number of decimal places in Swift?
I have:
var totalWorkTimeInHours = (totalWorkTime/60/60)
With totalWorkTime
being an NSTimeInterval (double) in second.
totalWorkTimeInHours
will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039……
How do I round this down to, say, 1.543 when I print totalWorkTimeInHours
?
Best Answer
You can use Swift's
round
function to accomplish this.To round a
Double
with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:Unlike any kind of
printf(...)
orString(format: ...)
solutions, the result of this operation is still of typeDouble
.Regarding the comments that it sometimes does not work, please read this: What Every Programmer Should Know About Floating-Point Arithmetic