NSNumberFormatter PercentStyle decimal places NSNumberFormatter PercentStyle decimal places swift swift

NSNumberFormatter PercentStyle decimal places


To set the number of fraction digits use:

percentFormatter.minimumFractionDigits = 1percentFormatter.maximumFractionDigits = 1

Set minimum and maximum to your needs. Should be self-explanatory.


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 Foundationlet percentFormatter = NumberFormatter()percentFormatter.numberStyle = NumberFormatter.Style.percentpercentFormatter.multiplier = 1percentFormatter.minimumFractionDigits = 1percentFormatter.maximumFractionDigits = 2let myDouble1: Double = 8let myString1 = percentFormatter.string(for: myDouble1)print(String(describing: myString1)) // Optional("8.0%")let myDouble2 = 8.5let myString2 = percentFormatter.string(for: myDouble2)print(String(describing: myString2)) // Optional("8.5%")let myDouble3 = 8.5786let myString3 = percentFormatter.string(for: myDouble3)print(String(describing: myString3)) // Optional("8.58%")


When in doubt, look in apple documentation for minimum fraction digits and maximum fraction digits which will give you these lines you have to add before formatting your number:

numberFormatter.minimumFractionDigits = 1numberFormatter.maximumFractionDigits = 2

Also notice, your input has to be 0.085 to get 8.5%. This is caused by the multiplier property, which is for percent style set to 100 by default.