I have a NumberFormatter
which has a currency number style. I can successfully format my number to string. However, when I try to get number from string, It returns null. The problem occurs when string has grouping separator.
My formatter:
let groupingSeparator = "."
let decimalSeparator = ","
let formatter = NumberFormatter()
formatter.maximumIntegerDigits = 6
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 0
formatter.numberStyle = .currency
formatter.groupingSize = 3
formatter.groupingSeparator = groupingSeparator
formatter.currencyGroupingSeparator = groupingSeparator
formatter.usesGroupingSeparator = true
formatter.decimalSeparator = decimalSeparator
formatter.currencyDecimalSeparator = decimalSeparator
formatter.currencySymbol = viewModel?.currency?.symbol ?? ""
How I try to get number from string:
if let number = amountFormatter.number(from: currentInput) {
text = amountFormatter.string(from: number)
}
Working Texts:
$1459
$2345,23
Not working Texts:
$1.459
$2.333,49
I suspect that your let constant
groupingSeparator
is empty. When I run the following code:I get the output
Exactly as expected.
(Note that I'm in the US, so the default output for
NSNumber.description
uses a "." decimal separator.)