Using NSNumberFormatter to pad spaces between a currency symbol and the value
Apologies if this is a dumb question but I'm trying to format a currency value for my iphone app and am struggling to left-justify the currency symbol, but right-justify the value. So, "$123.45" is formatted as (say)
$ 123.45depending on format-width. This is a kind of accounting format (I think).
I've tried various methods with NSNumberFormatter but can't get what I need.
开发者_运维技巧Can anyone advise on how to do this?
Thanks
Fitto
You're looking for the paddingPosition
property of NSNumberFormatter
. You need to set this to NSNumberFormatterPadAfterPrefix
for the desired format.
This didn't work for me. I was able to add a space between the currency symbol and the amount by doing this.
Swift 3.0
currencyFormatter.negativePrefix = "\(currencyFormatter.negativePrefix!) "
currencyFormatter.positivePrefix = "\(currencyFormatter.positivePrefix!) "
Complete code:
extension Int {
func amountStringInCurrency(currencyCode: String) -> (str: String, nr: Double) {
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.currencyCode = currencyCode
currencyFormatter.negativePrefix = "\(currencyFormatter.negativePrefix!) "
currencyFormatter.positivePrefix = "\(currencyFormatter.positivePrefix!) "
let nrOfDigits = currencyFormatter.maximumFractionDigits
let number: Double = Double(self)/pow(10, Double(nrOfDigits))
return (currencyFormatter.string(from: NSNumber(value: number))!, number)
}
}
This extension is on an Int that expresses the amount in MinorUnits. I.e. USD is expressed with 2 digits, while japanese yen is expressed without digits. So this is what this extension would return:
let amountInMinorUnits: Int = 1234
amountInMinorUnits.amountStringInCurrency(currencyCode: "USD").str // $ 12.34
amountInMinorUnits.amountStringInCurrency(currencyCode: "JPY").str // JP¥ 1,234
The thousand and decimal separator are determined by the users locale.
精彩评论