NSNumberFormatter paddingPosition不起作用 [英] NSNumberFormatter paddingPosition doesn't work
本文介绍了NSNumberFormatter paddingPosition不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的格式化货币值。 $ 99.99
。我需要在货币符号和金额之间留一个空格,例如 $ 99.99
。从这个 answer 中我发现我需要为此使用填充。但是我正在尝试的方法不起作用。
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
也许我缺少了什么?
推荐答案
该填充显示出来,您需要为格式化程序提供宽度:
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) "
这篇关于NSNumberFormatter paddingPosition不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文