我的应用程序中有一个欧元货币格式化程序。当用户最初将其从任何其他货币设置为欧元时,格式化程序将其显示为 €1000
。然而,当应用程序重新启动时,它会将其更改为 1000 €
,有时甚至会变成 €1000 €
!知道这里发生了什么吗?
func formatAsCurrency(currencyCode: String) -> String? {
let currencyFormatter = NSNumberFormatter()
let isWholeNumber: Bool = floor(self) == self
currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
currencyFormatter.maximumFractionDigits = isWholeNumber ? 0 : 2
currencyFormatter.minimumFractionDigits = isWholeNumber ? 0 : 2
currencyFormatter.locale = NSLocale(localeIdentifier: currencyCode)
if let currencyString = currencyFormatter.stringFromNumber(self) {
return currencyString
}
return nil
}
最佳答案
正如 lgor 所说,您想使用 currencyCode
而不是 locale
...这可以作为替代品吗?
extension Double {
/// Formats the receiver as a currency string using the specified three digit currencyCode. Currency codes are based on the ISO 4217 standard.
func formatAsCurrency(currencyCode: String) -> String? {
let currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
currencyFormatter.currencyCode = currencyCode
currencyFormatter.maximumFractionDigits = floor(self) == self ? 0 : 2
return currencyFormatter.stringFromNumber(self)
}
}
300.00.formatAsCurrency("GBP") // "£300"
129.92.formatAsCurrency("EUR") // "€129.92"
(-532.23).formatAsCurrency("USD") // "-$532.23"
同样值得指出的是,为什么您在修改 locale
时会看到奇怪的格式设置行为。通过更改 locale
,格式化程序会根据该本地化应用不同的格式化规则。
通常,您希望将区域设置保留为其默认值 (NSLocale.currentLocale()
),这样字符串的格式将本地化为用户语言。这通常用于 differences in decimal and thousand separators 之类的东西
如果您特别想要以特定方式格式化数字,那么您应该覆盖区域设置以确保内容保持一致。如果你担心正在使用什么分隔符,使用什么货币符号或者符号被放置在字符串中那么一定要将区域设置设置为特定的东西或者确保你覆盖 NSNumberFormatter< 上的所有相关属性
。
例如,如果我知道我希望我的数字格式化为美国英语语言环境,那么我会使用 NSLocale(localeIdentifier: "en_US_POSIX")
来确保它没有区别。如果您不介意它对您的用户来说更个性化一点,那么就不必费心指定语言环境。
关于ios - iOS 中的欧元货币格式化程序在数字之前/之后移动符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34134126/