开发者

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

开发者 https://www.devze.com 2022-12-21 18:01 出处:网络
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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消