Swift version: 5.2
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 ViRE offers discoverable way of working with regex. It provides really readable regex experience, code complete & cheat sheet, unit tests, powerful replace system, step-by-step search & replace, regex visual scheme, regex history & playground. ViRE is available on Mac & iPad.
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.