Precision String Format Specifier In Swift

Below is how I would have previously truncated a float to two decimal places

NSLog(@" %.02f %.02f %.02f", r, g, b);

I checked the docs and the eBook but haven’t been able to figure it out. Thanks!

31 Answers
31

The following code:

import Foundation // required for String(format: _, _)

print(String(format: "a float number: %.2f", 1.0321))

will output:

a float number: 1.03

Leave a Comment