Aside from overriding the current method that does the conversion to string, is there a nice way to round the double/string representation of it to 3 decimal places?
Asked
Active
Viewed 5,857 times
1
-
Do you want to round, or do you just want to chop off the digits after the 3rd? – nhgrif Jun 12 '14 at 21:31
1 Answers
4
You can create an extension, and then specify the precision as you call it.
extension Double {
func format(f: String) -> String {
return NSString(format: "%\(f)f", self)
}
}
let myDouble = 1.234567
println(myDouble.format(".3")

d.moncada
- 16,900
- 5
- 53
- 82
-
3This isn't rounding. This is simply displaying 3 decimal places without any rounding involved. Your answer will print `1.234` but were it rounded, it should print `1.235`. – nhgrif Jun 12 '14 at 21:31
-
thanks. amazing they didn't include things like this. not to mention no subscripting strings... – chris Jun 12 '14 at 21:33
-
7@nhgrif actually it does round, try it out in your playground. It maintains the C printf behavior which is to round to the requested digits. – David Berry Jun 12 '14 at 22:48