Nikhil Pandey
Nikhil Pandey

Reputation: 272

How to convert number inputted in any locale inside a UITextField into English number in iOS Swift

I am trying to get some decimal number from the user inside a UITextfield in iOS Swift. Now the user can input number in his or her local number format as per the locale Settings in iOS. I want to convert this number which is in the user's mother tongue into English number. I searched a lot in this site (stackoverflow.com) and the majority of answers are for conversion from one locale (Chinese, or Arabic or Persian) into English but I want to convert number inputted into any locale format into English. How can I do this? So in nutshell, my question is whether the number being inputted in UITextField is in Hindi, Arabic, Persian, Chinese or whatsoever format as per the locale, I want to convert it into English Number format.

Upvotes: 0

Views: 661

Answers (3)

Nikhil Pandey
Nikhil Pandey

Reputation: 272

Just to improve upon Dharmesh answer, here is the answer wrapped in a helper method for use throughout the code. Obviously, it assumes that while getting user input via UITextField one has considered the number set in the user's locale settings.

func convertLocaleNumberIntoEnglish(localeNumberString: String?) -> String? {

    guard let ulocaleNumberString = localeNumberString else {return nil}
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .decimal
    let localNumberInStr = ulocaleNumberString
    guard let number = numberFormatter.number(from: localNumberInStr) else {return nil}

    let str = String(format:"%f", number.doubleValue) 

    return str

}

Upvotes: 0

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

you can use NumberFormatter for that.

check below example:

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
let localNumberInStr = "૨૩"
guard let str = numberFormatter.number(from: localNumberInStr) else {return}
print(str)  //"23"

Upvotes: 1

Dennis
Dennis

Reputation: 288

When you check the devices locale you know which locale the user is using.

let locale = Locale.current

Upvotes: 1

Related Questions