Mulgard Mulgard - 4 years ago 114
Swift Question

Why is that an invalid number?

There are very different ways of displaying numbers, for example:

16666,67
16666.67
16.666,67
16.666.67


Those are all valid numbers for different regions and / or countries.
In our usecase we have to use following representation:

16.666.67


Because


  1. Its easier to see how big the number is using the thousands seperator

  2. We needed to prevent wrong user inputs so we are replacing all commas with a period



Though, for a numberformatter with a period as decimal sperator
16.666.67
is not a valid number:

self.numberFormatter = NumberFormatter()
self.numberFormatter.numberStyle = .decimal;
self.numberFormatter.minimumFractionDigits = 0;
self.numberFormatter.maximumFractionDigits = 2;
self.numberFormatter.decimalSeparator = ".";

print(self.numberFormatter.number(from: "16.666.67");


which is resulting in
nil
. Why is that an invalid number? And how can I solve that problem?'

EDIT

Following test:

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal;
numberFormatter.minimumFractionDigits = 0;
numberFormatter.maximumFractionDigits = 2;
numberFormatter.groupingSeparator = ".";
numberFormatter.decimalSeparator = ".";

print(numberFormatter.number(from: "16666"));
print(numberFormatter.number(from: "16666,67"));
print(numberFormatter.number(from: "16666.67"));
print(numberFormatter.number(from: "16.666"));
print(numberFormatter.number(from: "16.666,67"));
print(numberFormatter.number(from: "16.666.67"));


output is:

Optional(16666)
nil
Optional(16666.67)
Optional(16666)
nil
nil

dfd dfd
Answer Source

The issue is that the String 16.667.67 is no less an invalid number as This.is.a.number.00.

You need to make your String variable be something valid.

EDIT:

Based on the comments this sounds like a language behavior issue (Java versus Swift).

I'm seeing other comments on handling this, but to me, it looks like it gets down to how the Swift NumberFormatter automatically handles a String input with multiple decimal points. Unlike (some) other languages, you may need to do some pre-formatting of the string before calling NumberFormatter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download