singledev singledev - 1 year ago 102
iOS Question

NSDecimalNumber(string: ".") returns 0 (zero). Why?

This is Swift 3, Xcode 8.1

I was expect


Would that be a bug?

To illustrate:


Any ideas on how to handle "."?

I'd like to avoid things like:

if string == "." { ... }

guard string =! "." { ... }

Answer Source

0 is a valid input.

0. is a valid input`.

.0 is a valid input.

It's not so surprising that . is also a valid input. Strange, but not surprising and the value is well defined.

Note this is valid only if the character matches current locale, e.g. . will work with the English locale but not with German locale and viceversa:

Decimal(string: ".", locale: Locale(identifier: "de")) // NaN
Decimal(string: ",", locale: Locale(identifier: "de")) // Optional(0)

In short, both leading and trailing zeros can be omitted.

If you want to handle this value, I recommend to use regular expressions. Decide which formats are valid, write a regular expression for that formats and check the string with that regular expression.

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