Search code examples
iosswiftnsnumberformatter

Can I get exactly opposite result of NumberFormatter.Style.spellOut?


I want "eleven" to 11 and I am not getting the result through::

formatter.number(from: "String")

Solution

  • The .spellOut style option of NumberFormatter works in both ways.

    Note that if you want to parse "eleven" you need to set the appropriate Locale:

    formatter.locale = .init(identifier: "en_US")
    

    Then you can reverse the formatting using the same formatter:

    let formatter = NumberFormatter()
    formatter.locale = .init(identifier: "en_US")
    formatter.numberStyle = .spellOut
    if let number = formatter.number(from: "eleven") {
        print(number) // prints 11
    } else {
        // error
    }