Home » Swift » NSNumberFormatter PercentStyle decimal places

NSNumberFormatter PercentStyle decimal places

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’m using Swift

let myDouble = 8.5 as Double

let percentFormatter            = NSNumberFormatter()
percentFormatter.numberStyle    = NSNumberFormatterStyle.PercentStyle
percentFormatter.multiplier     = 1.00

let myString = percentFormatter.stringFromNumber(myDouble)!

println(myString)

Outputs 8% and not 8.5%, how would I get it to output 8.5%? (But only up to 2 decimal places)

Answers:

To set the number of fraction digits use:

percentFormatter.minimumFractionDigits = 1
percentFormatter.maximumFractionDigits = 1

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

Questions:
Answers:

With Swift 3, 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)
//let myString1 = percentFormatter.string(from: NSNumber(value: myDouble1)) // also works
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%")