Precision String Format Specifier In Swift


It is sometimes necessary to format strings in a custom format in order to use them in an application. For example, you can format product prices, decimal-point numbers, etc.

In Swift, you can use precision specifiers to specify the number of decimal places or the number of characters to be displayed in a string.

Example 1

To specify the number of decimal places for a floating-point number, you can use the %.nf format specifier, where n is the number of decimal places.,

import Foundation
let productPrice = 300.3456789
let formattedPrice = String(format: "%.2f", productPrice)
print("The formatted price is: ", formattedPrice)

Output

The formatted price is: 300.35

The "%f" format is a string but in the above example, "%.2f" means a floating-point number with two digits after the decimal point.

Example 2

You can also use the * character as a wildcard for the precision specifier, in which case the precision will be taken from the argument list.

import Foundation
let productPrice = 300.3456789
let precision = 3
let formattedPrice = String(format: "%.*f", precision, productPrice)
print("The formatted price is: ", formattedPrice)

Output

The formatted price is: 300.346

Using rounded() Function

The rounded() method rounds the specified value to the closest int or long value and returns it.

The Syntax of the Rounded() Method is

num.rounded()

Example

In this example, we are going to use rounded function and print the value to the closes int or long value.

import Foundation
let x = 16.40
print(x.rounded(.toNearestOrAwayFromZero))
// prints "16.0"
print(x.rounded(.towardZero))
// prints "16.0"
print(x.rounded(.up))
// prints "17.0"
print(x.rounded(.down))
// prints "16.0"

Output

16.0
16.0
17.0
16.0

Conclusion

The swift format specifier is very useful for converting the value and dealing with decimal values. You can format the double and floating values in any ways whatever you need.

Updated on: 03-Jan-2023

828 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements