首页 > 解决方案 > Localized currency symbol from NumberFormatter

问题描述

how to set NumberFormatter to return currency symbol not the iso one but local which is visible in iOS locale settings pane. Like for Polish currency I need to have “zł” symbol not the “PLN”.

I cannot find any way to get it from system as this cannot be hardcoded. IAP localized price also uses “zł” not “PLN”</p>

I tried this way:

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = Locale.current.currencySymbol
formatter.maximumFractionDigits = 2

let price = formatter.string(from: (offeringPrice / 12) as NSNumber) ?? ""

but whatever I try to use as currency symbol I always get in return "PLN"

标签: iosswiftnsnumberformatternumberformatter

解决方案


如果您设置formatter.localepl_PL有效:

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
formatter.currencyCode = "PLN"

let polandLocale = Locale(identifier: "pl_PL")
let usLocale = Locale(identifier: "en_US")

let offeringPrice = 50.0
let price = (offeringPrice / 12) as NSNumber

formatter.locale = usLocale
formatter.string(from: price) // "PLN 4.17"

formatter.locale = polandLocale
formatter.string(from: price) // "4,17 zł"

推荐阅读