If you’d like to interpolate a float or a double with a String in Swift, use the %f String format specifier with appropriate number in order to specify floating point precision.
Given a Float or a Double value:
var value = 4.53978
Create a string with value rounded to one decimal place which results in 4.5:
let stringValue = String(format: "Value: %.1f", value)
String with value rounded to two decimal places results in 4.54:
let stringValue = String(format: "Value: %.2f", value)
String with value rounded to three decimal places results in 4.540:
let stringValue = String(format: "Value: %.3f", value)
Note that Swift automatically rounds the value for you.
Related tutorials:
- How to convert String to Double or Float in Swift
- How to pick a random element from an array in Swift