Specify floating point precision in String in Swift

To specify a floating point precision in a string to display specific number of digits after decimal point in Swift, you can use the string interpolation.

For example, if you would like to display only two decimal places of float value x in a string str, then use the following syntax.

let str = String(format: "Value is %.2f", x)

You may change the value of 2 to other integer value, that represents the number of decimal places you would like to display in the string.

Examples

ADVERTISEMENT

1. Floating point precision of 2, in a string

In this example, we take a floating value in x, and display only two decimal places of this float value in a string str, using string interpolation.

main.swift

import Foundation

let x = 3.1415926
let str = String(format: "Value is %.2f", x)
print(str)

Output

Swift string - Floating point precision of 2

2. Floating point precision of 4, in a string

In this example, we shall display four decimal places of the float value x in a string str, using string interpolation.

main.swift

import Foundation

let x = 3.1415926
let str = String(format: "Value is %.4f", x)
print(str)

Output

Swift string - Floating point precision of 4

Conclusion

In this Swift Tutorial, we have seen how to specify a floating point precision in a string using string interpolation, with examples.