Using NSNumberFormatter to pad spaces between a currency symbol and the value

对着背影说爱祢 提交于 2020-01-05 11:14:25

问题


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.45
depending 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


回答1:


You're looking for the paddingPosition property of NSNumberFormatter. You need to set this to NSNumberFormatterPadAfterPrefix for the desired format.




回答2:


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.



来源:https://stackoverflow.com/questions/2352868/using-nsnumberformatter-to-pad-spaces-between-a-currency-symbol-and-the-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!