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
  • 60,448
  • 19
  • 148
  • 192
chris
  • 4,600
  • 4
  • 32
  • 64

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,032
  • 4
  • 49
  • 76
  • 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