If you need to print out a formatted string in C languages, you need some format specifiers like %d, %f or %@ in Objective-C to represent a format argument. Then you passing your content to be formatted to get the output. Take an example, we can use it in NSLog in Objective-C, which will log the formatted string to console:

int a = 3;
float b = 1.234567;
NSString *c = @"Hello";
NSLog(@"int:%d float:%f string:%@",a,b,c);
// Output:
// int:3 float:1.234567 string:Hello

In Swift, we often use print to log out, which is support string interpolation. When interpolating an instance in a string, its Streamable, Printable or DebugPrintable (in order) will be used to return a string value and be inserted into the string. By this, there is no need to remember the meaning of a format specifier, but simply use the interpolation to log strings. The equivalent code of above in Swift would be:

let a = 3;
let b = 1.234567
let c = "Hello"
print("int:\(a) double:\(b) string:\(c)")
// Output:
// int:3 double:1.234567 string:Hello

It is great that there is no need to remember the meaning of specifier, which is a burden of C. However, there is a situation you have to use these specifiers. If you only want to log b to only the second decimal, you can write this by using NSLog and Objective-C:

NSLog(@"float:%.2f",b);
// 输出:
// float:1.23

While in print in Swift, there is no luck. It is not compatible with format to decimal. The workaround is switching back to the original string formatting method, by using the init method of String:

let format = String(format:"%.2f",b)
print("double:\(format)")
// Output:
// double:1.23

Sure, it is quite boring if we write such things every time. If we need to use a lot of formatting like this, a better way would be using an extension on Double:

extension Double {
    func format(f: String) -> String {
        return String(format: "%\(f)f", self)
    }
}

Now, the code is cleaner:

let f = ".2"
print("double:\(b.format(f))")