With Swift 5, NumberFormatter
has an instance property called minimumFractionDigits
. minimumFractionDigits
has the following declaration:
var minimumFractionDigits: Int { get set }
The minimum number of digits after the decimal separator allowed as input and output by the receiver.
NumberFormatter
also has an instance property called maximumFractionDigits
. maximumFractionDigits
has the following declaration:
var maximumFractionDigits: Int { get set }
The maximum number of digits after the decimal separator allowed as input and output by the receiver.
The following Playground code shows how to use minimumFractionDigits
and maximumFractionDigits
in order to set the number of digits after the decimal separator when using NumberFormatter
:
import Foundation
let percentFormatter = NumberFormatter()
percentFormatter.numberStyle = NumberFormatter.Style.percent
percentFormatter.multiplier = 1
percentFormatter.minimumFractionDigits = 1
percentFormatter.maximumFractionDigits = 2
let myDouble1: Double = 8
let myString1 = percentFormatter.string(for: myDouble1)
print(String(describing: myString1)) // Optional("8.0%")
let myDouble2 = 8.5
let myString2 = percentFormatter.string(for: myDouble2)
print(String(describing: myString2)) // Optional("8.5%")
let myDouble3 = 8.5786
let myString3 = percentFormatter.string(for: myDouble3)
print(String(describing: myString3)) // Optional("8.58%")