การใช้ NSNumberFormatter เพื่อเว้นช่องว่างระหว่างสัญลักษณ์สกุลเงินและค่า

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

ฉันได้ลองวิธีการต่างๆ ด้วย NSNumberFormatter แล้ว แต่ไม่ได้สิ่งที่ต้องการ

ใครสามารถให้คำแนะนำเกี่ยวกับวิธีการทำเช่นนี้?

ขอบคุณ

ลงตัวกับ


person Fittoburst    schedule 28.02.2010    source แหล่งที่มา


คำตอบ (2)


คุณกำลังมองหาคุณสมบัติ paddingPosition ของ NSNumberFormatter คุณต้องตั้งค่านี้เป็น NSNumberFormatterPadAfterPrefix สำหรับรูปแบบที่ต้องการ

person Can Berk Güder    schedule 28.02.2010
comment
ฉลาดหลักแหลม. ทำงานรักษา ขอบคุณ - person Fittoburst; 02.03.2010
comment
สิ่งสำคัญที่ควรทราบคือวิธีนี้ใช้ได้เฉพาะเมื่อตั้งค่า formatWidth ตามคำถาม - person philippe; 24.05.2017

สิ่งนี้ไม่ได้ผลสำหรับฉัน ฉันสามารถเว้นวรรคระหว่างสัญลักษณ์สกุลเงินและจำนวนเงินได้โดยการทำเช่นนี้

สวิฟท์ 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)
    }
}

ส่วนขยายนี้อยู่ใน Int ที่แสดงจำนวนเงินเป็น MinorUnits เช่น. USD แสดงเป็นตัวเลข 2 หลัก ในขณะที่เงินเยนของญี่ปุ่นแสดงโดยไม่มีตัวเลข นี่คือสิ่งที่ส่วนขยายนี้จะกลับมา:

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

ตัวคั่นหลักพันและทศนิยมถูกกำหนดโดยโลแคลของผู้ใช้

person guido    schedule 14.12.2016