Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSNumberFormatter paddingPosition doesn't work

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?

like image 289
Isuru Avatar asked Nov 17 '15 15:11

Isuru


1 Answers

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) "
like image 137
Nate Cook Avatar answered Oct 18 '22 00:10

Nate Cook