Swift 3 中用于将英文数字转换为波斯语或阿拉伯数字的 NSFormatter

The NSFormatter for Converting English Number to persian or arabic Number in Swift 3

我在这里阅读了类似的问题并在我的应用程序中编写了这个方法

        let formatter = NumberFormatter()

    func convertEngNumToPersianNum(num: String)->String{
        let number = NSNumber(value: Int(num)!)
        let format = NumberFormatter()
        format.locale = Locale(identifier: "fa_IR")
        let faNumber = format.string(from: number)

        return faNumber!


    }

我没有得到错误但是我也没有得到结果!

我的号码代码是这样的:

let checkNumber = Home2ViewController().customtitle.count
    personalCustom.text = ("\(checkNumber)")

我在另一个可用的视图控制器中使用了另一个数字,但我想以波斯语或阿拉伯数字格式而不是英语格式显示此数字

试试这个:

func convertEngNumToPersianNum(num: String)->String{
        //let number = NSNumber(value: Int(num)!)
        let format = NumberFormatter()
        format.locale = Locale(identifier: "fa_IR") 
        let number =   format.number(from: num)
        let faNumber = format.string(from: number!)
        return faNumber!

    }

或替换为您的行

        let number =   format.number(from: num)
    let faNumber = format.string(from: number!)

你可以这样做,

    let formatter = NumberFormatter()
    formatter.locale = NSLocale.current   // you can specify locale that you want
    formatter.numberStyle = .decimal
    formatter.usesGroupingSeparator = true



    let number = formatter.number(from: "١٠.٠٠")

    print(number ?? "")

在保留前导零的同时转换为阿拉伯语

func convertToArDigits(_ digits: String) -> String {
            // We need a CFMutableString and a CFRange:
            let cfstr = NSMutableString(string: digits) as CFMutableString
            var range = CFRange(location: 0, length: CFStringGetLength(cfstr))
            // Do the transliteration (this mutates `cfstr`):
            CFStringTransform(cfstr, &range, kCFStringTransformLatinArabic, false)
            // Convert result back to a Swift string:
            return (cfstr as String)
        }
   extension String {
public var faToEnDigits : String {
    let farsiNumbers = ["٠": "0","١": "1","٢": "2","٣": "3","٤": "4","٥": "5","٦": "6","٧": "7","٨": "8","٩": "9"]
    var txt = self
    farsiNumbers.map { txt = txt.replacingOccurrences(of: [=10=], with: )}
    return txt
}
public var enToFaDigits : String {
    let englishNumbers = ["0": "۰","1": "۱","2": "۲","3": "۳","4": "۴","5": "۵","6": "۶","7": "۷","8": "۸","9": "۹"]
    var txt = self
    englishNumbers.map { txt = txt.replacingOccurrences(of: [=10=], with: )}
    return txt
}
}