iOS 中的欧元货币格式化程序移动符号 before/after 数字

Euro currency formatter in iOS moves symbol before/after number

我的应用程序中有欧元的货币格式化程序。当用户最初将其从任何其他货币设置为欧元时,格式化程序将其显示为 €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
}

使用 currencyCode/internationalCurrencySymbol currencyFormatter 的属性

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/#//apple_ref/occ/instp/NSNumberFormatter/currencyCode

http://useyourloaf.com/blog/using-number-formatters.html

正如 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")   // "-2.23"

同样值得指出的是,为什么您在修改 locale 时会看到奇怪的格式设置行为。通过更改 locale,格式化程序根据该本地化应用不同的格式化规则。

通常,您希望将区域设置保留为其默认值 (NSLocale.currentLocale()),这样字符串的格式将本地化为用户语言。这通常用于 differences in decimal and thousand separators

如果您特别想要以特定方式格式化数字,那么您应该覆盖语言环境以确保内容保持一致。如果您担心正在使用什么分隔符,使用什么货币符号或符号放在字符串中,请务必将区域设置设置为特定的内容或确保覆盖 NSNumberFormatter 上的所有相关属性.

例如,如果我知道我希望我的数字格式为美国英语语言环境,那么我会使用 NSLocale(localeIdentifier: "en_US_POSIX") 来确保它没有区别。如果您不介意它对您的用户来说更个性化一点,那么就不必费心指定语言环境。

您的问题是不同的国家以不同的方式显示欧元。 "Euro" 没有格式。有德国货币格式、法国货币格式、意大利货币格式等等,它们都以不同的方式显示欧元。