How to use println in Swift to format number
Asked Answered
S

4

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?

Shivers answered 8/6, 2014 at 3:47 Comment(2)
possible duplicate of Precision String Format Specifier In SwiftChe
possible duplicate of String formatting of a DoubleDihedral
S
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

Shivers answered 8/6, 2014 at 4:27 Comment(1)
println is removed in 2.0, use print insteadBea
G
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")
Grammer answered 8/6, 2014 at 4:1 Comment(5)
seems like a lot of work compared to using %.2f in Objective-CEducational
Yeah, I agree. There's definitely ways to make it more efficient such as with an extension, but it's still messy.Grammer
Agreed. There MUST be a simpler basic format string approach.Bilbrey
since Swift is still in beta, maybe inline string formatters haven't been implemented yetEducational
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.Grammer
D
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
Dynameter answered 14/5, 2015 at 8:26 Comment(1)
You have to put slash (\) before the "(round(avgTemp*100)/100)" to make it works. Like this: <code>print("average temp. = \(round(avgTemp*100)/100)")</code>Teirtza
N
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)")
Neoterize answered 11/11, 2015 at 16:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.