NSNumberFormatter paddingPosition doesn't work

家住魔仙堡 提交于 2019-12-10 16:35:29

问题


I have a formatted currency value like this. $99.99. I need to have a space in between the currency symbol and the amount like so $ 99.99. From this answer I found that I need to use padding for this. However what I'm trying isn't working.

private var currencyFormatter: NSNumberFormatter = {
    let formatter = NSNumberFormatter()
    formatter.numberStyle = .CurrencyStyle
    formatter.paddingPosition = .AfterPrefix
    return formatter
}()

var price: Float = 99.99


let s = currencyFormatter.stringFromNumber(price)
print(s!) // I still get $99.99

Maybe I'm missing something?


回答1:


In order to have that padding show up you'll need to provide a width to the formatter:

let currencyFormatter: NumberFormatter = {
    let formatter = NumberFormatter()
    formatter.numberStyle = .currency
    formatter.paddingPosition = .afterPrefix

    // pad with a space, use a minimum of seven characters
    formatter.paddingCharacter = " "
    formatter.formatWidth = 7

    return formatter
}()

print(currencyFormatter.stringFromNumber(99.99)!)
// prints "$ 99.99"

Alternately, if you just always need a single space you can try modifying the currency symbol:

formatter.currencySymbol = "\(formatter.currencySymbol) "


来源:https://stackoverflow.com/questions/33761272/nsnumberformatter-paddingposition-doesnt-work

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