5

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

        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)")

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

4

4 回答 4

7

试试这个 :

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!)
于 2017-05-16T05:45:09.023 回答
2

你可以做类似的事情,

    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 ?? "")
于 2017-05-16T05:49:01.040 回答
2
   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: $0, with: $1)}
    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: $0, with: $1)}
    return txt
}
}
于 2020-06-03T21:40:54.120 回答
1

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

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)
        }
于 2017-10-11T10:34:56.820 回答