Search code examples
iosswiftnsnumberformatter

Convert one Hindi language number to Arabic language number


I have come across one question Hindi numeric set Integer value in Swift

It was about how we can convert Hindi to English any number value.

Curious about to know how we can convert one language number to another language number

Like Example: trying to convert Hindi Language number to the Arabic language

Here is the code I have tried in the playground :

let string = "४"

let intParse1 = Int(string)

let numberFormat = NumberFormatter()
numberFormat.locale = Locale(identifier: "ar")

if let getOP = numberFormat.number(from: string) {
    print("output is: ", getOP)
}

Here is the output it is showing in the English only

enter image description here

I have searched for this problem but not found this kind of specific solution so posting a new question for it.

Note: Not looking for any static conversion extension or that kind of function.

EDIT: I don't want this kind of solution

convert arabic String to english number in Swift

EDIT 2:

I want to know about why we have to convert to it first to a number and then convert it to Arabic?, Means it is necessary to convert it first to English?


Solution

  • Explanation : NumberFormatter converts the number into another language number, not a string of a language to other language. So first we have to convert one language number number and then to another language number.

    Doc Explanation : Reference

    Instances of NumberFormatter format the textual representation of cells that contain NSNumber objects and convert textual representations of numeric values into NSNumber objects. The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position. NumberFormatter objects can also impose ranges on the numeric values cells can accept.

    Directly use this extension for Swift 4:

    extension String {
        func convertToArbic () -> String? {
            let formatter = NumberFormatter()
            formatter.locale = Locale(identifier: "hi")
            guard let number = formatter.number(from:self ) else{
                return nil
            }
            formatter.locale = Locale(identifier: "ar")
            guard let number2 = formatter.string(from: number) else{
                return nil
            }
            return number2
        }
    }
    
    // use
    let string = "४"
    if let arbNumber = string.convertToArbic() {
        print(arbNumber)
    }
    else{
        print("Unable to get arabic number")
    }
    

    Output:

    enter image description here