Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use println in Swift to format number

Tags:

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?

like image 822
sirab333 Avatar asked Jun 08 '14 03:06

sirab333


People also ask

How do I change the number format in Swift?

When you display a number in Swift (Float, Double, Int) it will display without grouping separators. By default a number like 4,592,028.0 will display like: 4592028.0 You need to use the NumberFormatter (NSNumberFormatter) class to convert your number into a pretty String for a text field.

What is Println in Swift?

The Swift 1's println function was replaced with the “print” function. In Swift 1, println would print a line of text, with a “newline” character at the end, so each call to println would be on a new line.

How do you round a string in Swift?

The "%f" format string means "a floating point number," but "%. 2f" means "a floating-point number with two digits after the decimal point. When you use this initializer, Swift will automatically round the final digit as needed based on the following number.


2 Answers

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

like image 64
sirab333 Avatar answered Oct 23 '22 09:10

sirab333


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") 
like image 43
Dash Avatar answered Oct 23 '22 11:10

Dash