Abid Hussain
Abid Hussain

Reputation: 1549

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

Upvotes: 0

Views: 690

Answers (2)

Rajeev
Rajeev

Reputation: 585

You can do as below:

let currency = str.trimmingCharacters(in: CharacterSet(charactersIn: "0123456789., "))

Upvotes: 3

Sharad Chauhan
Sharad Chauhan

Reputation: 4891

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

Upvotes: 2

Related Questions