Search code examples
iosswiftcocoa-touchnsnumberformatter

Swift: Getting currency symbol from an amount text


How can I extract currency symbol from strings which contain both amount and symbols. These strings can be in any international formats as I'm getting them from NumberFormatter. Some examples of such strings and their results are as follows:-

$446.99 =-> $

US$445,34 45 => US$

445,34 45 US$ => US$

THB567 => THB

567 THB => THB

and many more.

I already know about NumberFormatter properties currencySymbol, internationalCurrencySymbol but they don't help in getting to a universal solution as in case of US$ they return you $ and USD respectively. If there is any regex out there then I'm happy to try that too.

PS: I need this information to format my currency symbols according to following pic:- enter image description here


Solution

  • This is one of the methods which filter out the mention characters from a String:

    let filteredString = String("567 THB".filter { String($0).rangeOfCharacter(from: CharacterSet(charactersIn: "0123456789.,")) == nil }).trimmingCharacters(in: .whitespacesAndNewlines)
    //TBH <- prints