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.
Sponsored You’re already busy updating your app for Swift 4.2 and iOS 12, so why not let Instabug help you find and fix bugs? Add just two lines of code to your project and receive comprehensive reports with all the feedback you need to ship a world-class app – click here to learn more!
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.
Get the ultimate experience
The Swift Power Pack includes my first six books for one low price, helping you jumpstart a new career in iOS development – check it out!