1

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?

Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
chris
  • 4,840
  • 5
  • 35
  • 66

1 Answers1

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
  • 3
    This 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