25

When logging-out a float in Objective-C you can do the following to limit your output to only 2 decimal places:

float avgTemp = 66.844322156
NSLog (@"average temp. = %.2f", avgTemp);

But how do you do this in Swift? And how do you escape other characters in println in Swift?

Here's a regular Swift println statement:

println ("Avg. temp = \(avgTemp)")

So how do you limit decimal places?

Also, how do you escape double-quotes in println?

wigging
  • 8,492
  • 12
  • 75
  • 117
sirab333
  • 3,662
  • 8
  • 41
  • 54
  • 2
    possible duplicate of [Precision String Format Specifier In Swift](http://stackoverflow.com/questions/24051314/precision-string-format-specifier-in-swift) – Connor Pearson Jun 08 '14 at 03:51
  • possible duplicate of [String formatting of a Double](http://stackoverflow.com/questions/24047374/string-formatting-of-a-double) – Jukka Suomela Jun 12 '14 at 21:53

4 Answers4

28

Here's the shortest solution I found thus far:

let avgTemp = 66.844322156
println(NSString(format:"%.2f", avgTemp))

Its like the swift version of NSString's stringWithFormat

onevcat
  • 4,591
  • 1
  • 25
  • 31
sirab333
  • 3,662
  • 8
  • 41
  • 54
11

Everything about the format of a number as a string can be adjusted using a NSNumberFormatter:

let nf = NSNumberFormatter()
nf.numberStyle = NSNumberFormatterStyle.DecimalStyle
nf.maximumFractionDigits = 2
println(nf.stringFromNumber(0.33333)) // prints 0.33

You can escape quotes with a backslash

println("\"God is dead\" -Nietzsche")
Dash
  • 17,188
  • 6
  • 48
  • 49
  • 4
    seems like a lot of work compared to using `%.2f` in Objective-C – wigging Jun 08 '14 at 04:10
  • Yeah, I agree. There's definitely ways to make it more efficient such as with an extension, but it's still messy. – Dash Jun 08 '14 at 04:12
  • Agreed. There MUST be a simpler basic format string approach. – uchuugaka Jun 08 '14 at 04:12
  • since Swift is still in beta, maybe inline string formatters haven't been implemented yet – wigging Jun 08 '14 at 04:14
  • The \\() notation literally accesses the description property of whatever value is inside it. It would be cool to have the ability to include other formatting arguments but for now at least that would all have to be done manually. – Dash Jun 08 '14 at 04:17
8

Println() is deprecated.

 var avgTemp = 66.844322156
  print("average temp. = (round(avgTemp*100)/100)")   // average temp. = 66.84

//or

print(NSString(format:"average temp. = %.2f", avgTemp))) // average temp. = 66.84 avgTemp = 66.846322156

print(String(format:"average temp. = %.2f", avgTemp)) // average temp. = 66.85
Vicky
  • 602
  • 5
  • 16
  • You have to put slash (\\) before the "(round(avgTemp*100)/100)" to make it works. Like this: print("average temp. = \\(round(avgTemp*100)/100)") – Demilitarized Zone Aug 16 '16 at 00:50
0

If you need to print floating point numbers often with a certain precision, you could extend Float and Double with convenience methods. For example, for 2 significant figure precision:

// get Float or Double with 2 significant figure precision
var numberFormatter = NSNumberFormatter()
extension Float {
    var sf2:String {
        get {
            numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
            numberFormatter.maximumSignificantDigits = 2
            return numberFormatter.stringFromNumber(self)!
        }
    }
}
extension Double {
    var sf2:String {
        get {
            numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
            numberFormatter.maximumSignificantDigits = 2
            return numberFormatter.stringFromNumber(self)!
        }
    }
}

Then when you need to print things:

let x = 5.23325
print("The value of x is \(x.sf2)")
Daniel Howard
  • 4,330
  • 3
  • 30
  • 23