Trying to convert String to Currency with fatal error result

124 views Asked by At

I'm trying to create a simple function that converts a string into the local currency of the user.

I have a function that looks like this:

func decimalFormat(stringNumber:String) -> Decimal{
    print("\(stringNumber) is the number being passed")
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .currency
    let number = numberFormatter.number(from: stringNumber)
    print("\(number!) is the number")

    let amount = number?.decimalValue
    return amount!
}

For some reason I'm getting the unexpectedly found nil while unwrapping an Optional Value.

the first print works and gives me back what I pass into the function

decimalFormat("5.4")
print("\(stringNumber) is the number being passed") -> 5.4

So I think the error is coming from this line, just not sure why as I don't think there is an Optional Value you there to unwrap:

let number = numberFormatter.number(from: stringNumber)
0

There are 0 answers