gpt4 book ai didi

ios - 如何在Swift 3中将NSFormatter数字用于数组中的波斯或阿拉伯数字?

转载 作者:行者123 更新时间:2023-12-01 19:53:05 24 4
gpt4 key购买 nike

我知道如何使用NSFormatter Number将英语数字转换为波斯/阿拉伯数字,但是问题是我有一个数组,并且想要将数组中的所有数字转换为波斯/阿拉伯数字。

我怎样才能做到这一点?
请帮忙。

这是一个数字的代码:

let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "fa")
numberFormatter.numberStyle = NumberFormatter.Style.decimal

numberFormatter.string(from: NSNumber(value: checkNumber))
let persianNumber = numberFormatter.string(from: NSNumber(value: checkNumber))!

如您所见,我可以转换一个数字(checkNumber是英文数字,​​persianNumber是波斯/阿拉伯数字)

最佳答案

创建swift文件并附加此扩展名

extension String {


func englishToPersian() -> String{
var sum = ""
let letters = self.characters.map { String($0) }
for letter in letters {
if (Int(letter) != nil) {
let persianNumber = ["۰","۱","۲","۳","۴","۵","۶","۷","۸","۹"]
sum = sum+persianNumber[Int("\(letter)")!]
} else {
sum = sum+letter
}
}
return sum
}

func persianToEnglish() -> String{
var sum = ""
let letters = self.characters.map { String($0) }
let persianNumber = ["۰","۱","۲","۳","۴","۵","۶","۷","۸","۹"]
for letter in letters {
for (index, element) in persianNumber.enumerated() {
if letter == element {
sum = sum + "\(index)"
}
}
}
return sum
}

}
使用这个😊
let strEnglish1 = "1234567890"
strEnglish1.englishToPersian() // ۱۲۳۴۵۶۷۸۹۰

let strEnglish2 = "1200 toman"
strEnglish2.englishToPersian() // ۱۲۰۰ toman

let strPersian1 = "۱۲۳۴۵۶۷۸۹۰"
strPersian1.persianToEnglish() // 1234567890

let strPersian2 = "۱۲۰۰ تومان"
strPersian1.persianToEnglish() // ۱۲۰۰ تومان

关于ios - 如何在Swift 3中将NSFormatter数字用于数组中的波斯或阿拉伯数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44613916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com