How to convert english numbers inside a string to Persian/Arabic numbers in Objective-C?

前端 未结 10 1989
轮回少年
轮回少年 2021-01-18 10:53

I have an english string that may or may not have numbers. But i want those numbers to be printed on screen as Persian numbers.

For example if NSString *foo =

10条回答
  •  天涯浪人
    2021-01-18 11:33

    Swift 3:

    However other answers are correct, there is a little problem in converting String to Int.

    Converting a String to Int removes left zeros which is not good (Specially in converting cell phones and national Ids). To avoid this problem I prefer replacing each English number to Persian.

    static func convertToPersian(text : String)-> String {
        let numbersDictionary : Dictionary = ["0" : "۰","1" : "۱", "2" : "۲", "3" : "۳", "4" : "۴", "5" : "۵", "6" : "۶", "7" : "۷", "8" : "۸", "9" : "۹"]
        var str : String = text
    
        for (key,value) in numbersDictionary {
            str =  str.replacingOccurrences(of: key, with: value)
        }
    
        return str
    }
    

    This method can also be used to replace numbers within text and its not necessary to have a pure number to convert to Persian.

提交回复
热议问题