How can I show "$" instead of "US$" in NSnumberFormatter?

634 Views Asked by At

I used below code for conversion from NSnumber to currency with locale.

let price = 12.34 as NSNumber
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = "USD"
formatter.locale = NSLocale(localeIdentifier: "zh_CN") as Locale
print(formatter.string(from: price)!)

Expected Output: $12.34 , Actual Output: US$12.34

Could you please help me to resolve this behaviour.

1

There are 1 best solutions below

0
Dávid Pásztor On

If you want a currency symbol other than the default for the currency code and Locale, you can manually specify that using the currencySymbol property of NumberFormatter.

let price = 12.34
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencyCode = "USD"
formatter.locale = Locale(identifier: "zh_CN")
formatter.currencySymbol = "$"
print(formatter.string(for: price) ?? "nil") // "$12.34"

Other improvements to your code: don't use NSLocale in Swift, use Locale instead, especially when you cast the NSLocale to Locale immediately. You don't need to convert numbers to NSNumber just to format them either, you simply need to call NumberFormatter.string(for:) instead of string(from:) when using numeric types other than NSNumber.