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
?
The best way to format a double property is to use the Apple predefined methods.
FloatingPointRoundingRule is a enum which has following possibilities
Enumeration Cases:
case awayFromZero Round to the closest allowed value whose magnitude is greater than or equal to that of the source.
case down Round to the closest allowed value that is less than or equal to the source.
case toNearestOrAwayFromZero Round to the closest allowed value; if two values are equally close, the one with greater magnitude is chosen.
case toNearestOrEven Round to the closest allowed value; if two values are equally close, the even one is chosen.
case towardZero Round to the closest allowed value whose magnitude is less than or equal to that of the source.
case up Round to the closest allowed value that is greater than or equal to the source.
This is a sort of a long workaround, which may come in handy if your needs are a little more complex. You can use a number formatter in Swift.
Suppose your variable you want to print is
This will make sure it is returned in the desired format:
The result here will thus be "3.6" (rounded). While this is not the most economic solution, I give it because the OP mentioned printing (in which case a String is not undesirable), and because this class allows for multiple parameters to be set.
The code for specific digits after decimals is:
Here the %.3f tells the swift to make this number rounded to 3 decimal places.and if you want double number, you may use this code:
var roundedString = Double(String(format: "%.3f", b))
Use the built in Foundation Darwin library
SWIFT 3
Usage:
Outputs: 12.988
round a double value to x number of decimal
NO. of digits after decimal
Either:
Using
String(format:)
:Typecast
Double
toString
with%.3f
format specifier and then back toDouble
Or extend
Double
to handle N-Decimal places:By calculation
multiply with 10^3, round it and then divide by 10^3...
Or extend
Double
to handle N-Decimal places: