2

抱歉,如果这是一个愚蠢的问题,但我正在尝试为我的 iphone 应用程序格式化货币值并且正在努力左对齐货币符号,但右对齐值。因此,“$123.45”的格式为(比如说)

123.45 美元
取决于格式宽度。这是一种会计格式(我认为)。

我用 NSNumberFormatter 尝试了各种方法,但无法得到我需要的东西。

谁能建议如何做到这一点?

谢谢

适合

4

2 回答 2

6

您正在寻找 的paddingPosition财产NSNumberFormatter。您需要将其设置NSNumberFormatterPadAfterPrefix为所需的格式。

于 2010-02-28T22:22:05.270 回答
4

这对我不起作用。通过这样做,我可以在货币符号和金额之间添加一个空格。

斯威夫特 3.0

currencyFormatter.negativePrefix = "\(currencyFormatter.negativePrefix!) "
currencyFormatter.positivePrefix = "\(currencyFormatter.positivePrefix!) "

完整代码:

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)
    }
}

此扩展位于以 MinorUnits 表示数量的 Int 上。即美元用2位数字表示,而日元则不用数字表示。所以这就是这个扩展将返回的内容:

let amountInMinorUnits: Int = 1234
amountInMinorUnits.amountStringInCurrency(currencyCode: "USD").str // $ 12.34
amountInMinorUnits.amountStringInCurrency(currencyCode: "JPY").str // JP¥ 1,234

千位和小数点分隔符由用户区域设置确定。

于 2016-12-14T19:00:42.353 回答