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
?
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:Other than any kind of
printf(...)
orString(format: ...)
solutions, the result of this operation is still of typeDouble
.EDIT:
Regarding the comments that it sometimes does not work, please read this:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
With Swift 4.2, according to your needs, you can choose one of the 9 following styles in order to have a rounded result from a
Double
.#1. Using
FloatingPoint
rounded()
methodIn the simplest case, you may use the
Double
round()
method.#2. Using
FloatingPoint
rounded(_:)
method#3. Using Darwin
round
functionFoundation offers a
round
function via Darwin.#4. Using a
Double
extension custom method builded with Darwinround
andpow
functionsIf you want to repeat the previous operation many times, refactoring your code can be a good idea.
#5. Using
NSDecimalNumber
rounding(accordingToBehavior:)
methodIf needed,
NSDecimalNumber
offers a verbose but powerful solution for rounding decimal numbers.#6. Using
NSDecimalRound(_:_:_:_:)
function#7. Using
NSString
init(format:arguments:)
initializerIf you want to return a
NSString
from your rounding operation, usingNSString
initializer is a simple but efficient solution.#8. Using
String
init(format:_:)
initializerSwift’s
String
type is bridged with Foundation’sNSString
class (you can learn more about it by reading The Swift Programming Language). Therefore, you can use the following code in order to return aString
from your rounding operation:#9. Using
NumberFormatter
If you expect to get a
String?
from your rounding operation,NumberFormatter
offers a highly customizable solution.I would use
and change .3f to any number of decimal numbers you need
In Swift 2.0 and Xcode 7.2:
Example:
A handy way can be the use of extension of type Double
Usage: