1

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)
pacification
  • 5,838
  • 4
  • 29
  • 51
icekomo
  • 9,328
  • 7
  • 31
  • 59
  • 2
    `5.4` is not a valid currency string. A currency string has a currency symbol. Use `.decimal` as the `numberStyle` if you wish to parse non-currency number strings. – rmaddy Sep 13 '17 at 04:31
  • 2
    Your crash is on the 2nd `print` line because you are force-unwrapping a nil variable. Don't do that. – rmaddy Sep 13 '17 at 04:32
  • https://stackoverflow.com/questions/29782982/how-to-input-currency-format-on-a-text-field-from-right-to-left-using-swift/29783546#29783546 – Leo Dabus Sep 13 '17 at 05:18
  • Please update your question with what you expect the inputs and outputs of the function to be. The function currently returns a Decimal, but that is not a formatted currency. Or are you trying to convert from one currency to another? Your question is not clear. – picciano Apr 19 '18 at 14:35

0 Answers0