【问题标题】:Euro currency formatter in iOS moves symbol before/after numberiOS中的欧元货币格式化程序在数字之前/之后移动符号
【发布时间】:2015-12-07 12:57:35
【问题描述】:

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

【问题讨论】:

  • 从货币代码(例如 GBP)创建 NSLocale 不会返回有效的语言环境。有关支持的标识符,请参阅 NSLocale.availableLocaleIdentifiers()
  • 我传入en_GB 或我需要的任何语言环境标识符。它只是从我实际上确实在某一时刻通过英镑(这给我带来了一些奇怪的问题)起的糟糕命名。谢谢指出,我会解决的

标签: ios swift currency


【解决方案1】:

正如 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") 来确保它不会有所不同。如果您不介意它对您的用户来说更加个性化,那么不要费心指定区域设置。

【讨论】:

  • 我实际上只是将我的更改为这个 :) 我遇到的问题是由于在一种情况下手动添加货币符号。这也导致了我之前遇到的问题,这就是为什么我首先放弃了货币代码!
  • 是的,我将回到使用语言环境.. 使用货币代码将其格式化为US$1,000。我只想要$
  • 如果您想要精确,将货币值存储为 Double 不是一个好主意。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    【讨论】:

    • 这给我在货币之间切换时带来了其他问题 - 在某些情况下,它最终变成了£S$......不过我已经解决了我的问题。结果在一种情况下,符号被错误地手动添加,而不是使用格式化程序
    猜你喜欢
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多