为什么SwiftNumberFormatter需要一个不间断的空间才能正常工作?
我有一个带有掩码格式的UITextField将我的输入格式化为 BRL 货币,因此 从键盘输入1700 会产生1.700,00雷亚尔的文本,但由于我需要将此值设为双精度,因此NumberFormatter 的使用方式如下:
var currencyFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "pt_BR")
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 2
return formatter
}
但是当我尝试转换为 NSNumber 时,它给了我零。
let input = "R$ 1.700,00"
currencyFormatter.number(from: input) // prints nil
奇怪的是,转换器在提供数字时工作,并且字符串结果可以转换为数字。
let string = currencyFormatter.string(from: NSNumber(1700.00)) // prints "R$ 1.700,00"
currencyFormatter.number(from: string) // prints 1700.00
我开始调查并从下面的代码中找出我的输入和生成的currencyFormatter 字符串之间的区别。
let difference = zip(input, string).filter{ $0 != $1 } // Prints [(" ", " ")]
它可能看起来相同,但currencyFormatter在货币符号后生成一个带有不间断空格的字符串,而我的输入具有正常空格。用不间断空格替换我的输入空间使格式化程序正常工作。
let nonBreakingSpace = "u{00a0}"
let whitespace = " "
var convertedInput = "R$ 1.700,00".replacingOccurrences(of: whitespace, with: nonBreakingSpace) // prints R$ 1.700,00 or R$u{00a0}1.700,00
currencyFormatter.number(from: convertedInput) // Now it works and prints 1700.00
最后我的问题是,为什么在这种情况下,带有货币 numberStyle 的 NumberFormatter 只能使用不间断空格?
THE END
二维码