2010-02-28 58 views
0

道歉,如果這是一個愚蠢的問題,但我想格式化爲我的iPhone應用程序的貨幣價值之間墊空間很努力左對齊的貨幣符號,但右證明價值。因此,「$; 123.45&」被格式化爲(比方說)使用NSNumberFormatter一個貨幣符號和價值

$ 123.45
取決於格式的寬度。這是一種會計格式(我認爲)。

我試着NSNumberFormatter各種方法,但不能得到我所需要的。

任何人都可以建議如何做到這一點?

感謝

飛圖

回答

3

您正在尋找的NSNumberFormatterpaddingPosition財產。您需要將其設置爲NSNumberFormatterPadAfterPrefix以獲取所需的格式。

+0

輝煌。工作過一種享受。由於 – Fittoburst 2010-03-01 21:05:54

+0

需要注意的是,當formatWidth設置,按問題這隻能是很重要的。 – philippe 2017-05-24 14:54:03

0

這並沒有爲我工作。通過這樣做,我能夠在貨幣符號和金額之間添加一個空格。

夫特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 = NumberFormatter.Style.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) 
    } 
} 

該擴展是在一個Int表達在MinorUnits量。即美元以2位數字表示,而日元以數字表示。因此,這是此擴展將返回的內容:

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

千位和小數點分隔符由用戶區域設置確定。