NSNumberFormatter PercentStyle 小数位

NSNumberFormatter PercentStyle decimal places

我正在使用 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)

输出8%而不是8.5%,我如何让它输出8.5%? (但最多只能保留 2 位小数)

要设置小数位数,请使用:

percentFormatter.minimumFractionDigits = 1
percentFormatter.maximumFractionDigits = 1

根据需要设置最小值和最大值。应该是不言自明的。

对于 Swift 5,NumberFormatter 有一个名为 minimumFractionDigits 的实例 属性。 minimumFractionDigits 有以下声明:

var minimumFractionDigits: Int { get set }

The minimum number of digits after the decimal separator allowed as input and output by the receiver.


NumberFormatter 也有一个名为 maximumFractionDigits 的实例 属性。 maximumFractionDigits 具有以下声明:

var maximumFractionDigits: Int { get set }

The maximum number of digits after the decimal separator allowed as input and output by the receiver.


以下 Playground 代码显示了如何使用 minimumFractionDigitsmaximumFractionDigits 以便在使用 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%")

如有疑问,请查看 minimum fraction digits and maximum fraction digits 的 Apple 文档,其中会为您提供在格式化号码之前必须添加的这些行:

numberFormatter.minimumFractionDigits = 1
numberFormatter.maximumFractionDigits = 2

另请注意,您的 input has to be 0.085 to get 8.5%. This is caused by the multiplier property,百分比样式默认设置为 100。