Swift version: 5.4
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 From August 2nd to 8th you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!
Available from iOS 7.0
This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.
Link copied to your pasteboard.