【问题标题】:Avoiding non breaking space using NumberFormatter使用 NumberFormatter 避免非中断空间
【发布时间】:2021-03-07 10:23:42
【问题描述】:

我有一个NumberFormatter 设置,如下所示:

let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.groupingSeparator = "."
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale(identifier: "it_IT")
currencyFormatter.currencySymbol = ""

我需要根据输入的字符串值检索一个值。

currencyFormatter.number(from: "1.000,00") // nil
currencyFormatter.number(from: "1.000,00\u{00a0}") // 1000

在第一个示例中,格式化程序返回nil,而在第二个示例中,我获得了正确的值(\u{00a0} 是非中断空格符号)。

有没有办法让第一个示例在不添加空格符号的情况下工作?

【问题讨论】:

  • 毫无意义。您指的是两种不同的格式化程序,currencyFormatterformatter
  • @matt 我写这个问题的错误。固定

标签: swift number-formatting nsnumberformatter


【解决方案1】:

如果没有货币符号,则此数字格式化程序的样式需要为.decimal,而不是.currency。这就足够了:

let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .decimal
currencyFormatter.locale = Locale(identifier: "it_IT")

【讨论】:

  • 确实,如果您说.currency,格式化程序对于它将接受的内容变得非常挑剔(正如您已经发现的那样)。它需要一个空格,后面跟着一个欧元符号,没有其他东西可以做。我不知道为什么不间断的空间会颠覆它。但关键是,如果你说.decimal,你的两个输入都有效。
猜你喜欢
  • 2013-05-02
  • 1970-01-01
  • 2016-02-18
  • 2011-10-31
  • 2011-08-16
  • 2016-12-04
  • 1970-01-01
  • 2021-10-04
  • 1970-01-01
相关资源
最近更新 更多