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
?
Building on Yogi's answer, here's a Swift function that does the job:
If you want to round
Double
values, you might want to use SwiftDecimal
so you don't introduce any errors that can crop up when trying to math with these rounded values. If you useDecimal
, it can accurately represent decimal values of that rounded floating point value.So you can do:
Then, you can get the rounded
Decimal
value like so:And if you want to display it with a specified number of decimal places (as well as localize the string for the user's current locale), you can use a
NumberFormatter
:This is fully worked code
Swift 3.0/4.0 , Xcode 9.0 GM/9.2
output - 123
output - 123.3
output - 123.33
output - 123.326
Not Swift but I'm sure you get the idea.
Extension for Swift 2
A more general solution is the following extension, which works with Swift 2 & iOS 9:
Extension for Swift 3
In Swift 3
round
is replaced byrounded
:Example which returns Double rounded to 4 decimal places:
This is more flexible algorithm of rounding to N significant digits
Swift 3 solution