Swift's string interpolation makes it easy to put floating-point numbers into a string, but it lacks the ability to specify precision. For example, if a number is 45.6789, you might only want to show two digits after the decimal place.
Here's an example using basic string interpolation:
let angle = 45.6789 let raw = "Angle: \(angle)"
That will make the
raw value equal to "Angle: 45.6789". But if you wanted to round the angle to two decimal places, you would use this code instead:
let formatted = String(format: "Angle: %.2f", angle)
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.
Available from iOS 7.0
Did this solution work for you? Please pass it on!
Other people are reading…
About the Swift Knowledge Base
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Want to build macOS apps?
Hacking with macOS delivers 18 awesome projects that teach you macOS development in no time – take control of your desktop today!