1

In my case I have string with coma.

var stringWithComa = "1,2"

When I try to convert it to Float or Double I receive nil as expected.

Float(stringWithComa)//nil

Double(stringWithComa)//nil

But when I do Decimal(string: stringWithComa) I receive 1.

Why this issue is happening ?

3
  • Apparently Decimal(string:) just stops parsing as soon as an invalid character is found. Decimal(string: "1.23💣") returns 1.23 without exploding. Commented Feb 22, 2018 at 9:39
  • @MartinR I am a bit confused due to that implementation. Because seams to me in method Decimal(string:) implementation they also take current locale of the user but without respecting of the locale decimal separator. Commented Feb 22, 2018 at 9:51
  • If you want to the the current locale into account then you'll have to call Decimal(string: stringWithComma, locale: .current) Commented Feb 22, 2018 at 9:52

2 Answers 2

1

Use Decimal(string:locale:) to parse a string containing a localized number. Example:

print(Locale.current.decimalSeparator!) // ","

let stringWithComma = "1,2"
if let dec = Decimal(string: stringWithComma, locale: .current) {
    print(dec) // 1.2
}

Otherwise the comma is considered as an invalid character. Contrary to the Float and Double initializers, leading whitespace and trailing “junk” is ignored. The conversion succeeds if at least one valid character was found:

print(Decimal(string: "   1.23💣")) // Optional(1.23)
print(Decimal(string: "😈")) // nil
Sign up to request clarification or add additional context in comments.

Comments

1

The Decimal(string: String) constructor in swift will keep on parsing the provided string. If It finds any invalid character which cannot be evaluated, it will stop parsing.

A few examples -

Decimal(string: "34234.43423.4343") => "34234.43423"

Decimal(string: "#343.43") => nil

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.