如何在swift中将阿拉伯数字转换为英文数字?

时间:2017-01-16 01:21:25

标签: ios swift uitextfield

在我的应用中,我有5个uitextfields。我的预期用户是阿拉伯语用户,因此当他们使用我的应用程序时,他们将插入英文或阿拉伯语的数字。

该应用程序适用于英文数字。但是,当我运行它并在阿拉伯语中插入数字时,该应用程序会处理文本字段,就好像它们都是空的并将答案显示为0

如何确保文本字段不是nill和double,而不是忽略阿拉伯数字?

这是“calButton”函数中的代码:

     /*let value1 = Double(income.text ?? "") ?? 0
    let value2 = Double(salaries.text ?? "") ?? 0
    let value3 = Double(tools.text ?? "") ?? 0
    let value4 = Double(maintinance.text ?? "") ?? 0
    let value5 = Double(otherExpenses.text ?? "") ?? 0
    let sum = value1 - ( value2 + value3 + value4 + value5)

    print("result is: \(sum)")*/



    let textFields = [income, salaries, tools, maintinance, otherExpenses]
    var sum = 0.0
    for textField in textFields {
        if let number = Double((textField?.text!)!) { //checks that it is not nil AND a Double
            sum += number
        }
    }

    expensesTotal.text = String(sum)
    // print("result is: \(sum)")

5 个答案:

答案 0 :(得分:10)

您需要先将阿拉伯数字字符串转换为英语,然后再进行计算。

<extension>
  <modules>
    <module>
      <id>Menu customisation</id>
      <auto-deploy>true</auto-deploy>
      <evaluator type="default.extensibility.evaluator"/>
       <!-- default.extensibility.evaluator is applied to determine if the module should be executed -->
      <customizations>        
         <customization>
            <targetPackageRoot>org.alfresco</targetPackageRoot>
            <sourcePackageRoot>com.quanticate.header</sourcePackageRoot> <!-- Your package path should go here -->
            <alwaysApply>
               <webscript>share-header</webscript>
            </alwaysApply>
         </customization>
      </customizations>
    </module>
  </modules>
</extension>

答案 1 :(得分:3)

所有非拉丁字符串出现的Swift-5解决方案。

extension String {
    var containsNonEnglishNumbers: Bool {
        return !isEmpty && range(of: "[^0-9]", options: .regularExpression) == nil
    }

    var english: String {
        return self.applyingTransform(StringTransform.toLatin, reverse: false) ?? self
    }
}

用法-

textField.addTarget(self, action: #selector(didChangeText(field:)), for: .editingChanged)

@objc func didChangeText(field: UITextField) {
    if ((field.text?.containsNonEnglishNumbers) != nil) {
        field.text = field.text?.english
    }
}

答案 2 :(得分:3)

从任何语言到任何语言

具有以下扩展名,您可以做到:

extension String {
    private static let formatter = NumberFormatter()

    func clippingCharacters(in characterSet: CharacterSet) -> String {
        components(separatedBy: characterSet).joined()
    }

    func convertedDigitsToLocale(_ locale: Locale = .current) -> String {
        let digits = Set(clippingCharacters(in: CharacterSet.decimalDigits.inverted))
        guard !digits.isEmpty else { return self }

        Self.formatter.locale = locale
        let maps: [(original: String, converted: String)] = digits.map {
            let original = String($0)
            guard let digit = Self.formatter.number(from: String($0)) else {
                assertionFailure("Can not convert to number from: \(original)")
                return (original, original)
            }
            guard let localized = Self.formatter.string(from: digit) else {
                assertionFailure("Can not convert to string from: \(digit)")
                return (original, original)
            }
            return (original, localized)
        }

        var converted = self
        for map in maps { converted = converted.replacingOccurrences(of: map.original, with: map.converted) }
        return converted
    }
}

用法

"12345".convertedDigitsToLocale(Locale(identifier: "FA")) /* ۱۲۳۴۵ */
"۱۲۳۴۵".convertedDigitsToLocale(Locale(identifier: "EN")) /* 12345 */

答案 3 :(得分:2)

这会将阿拉伯数字替换为英语

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField.keyboardType == .numberPad && string != "" {
            let numberStr: String = string
            let formatter: NumberFormatter = NumberFormatter()
            formatter.locale = Locale(identifier: "EN")
            if let final = formatter.number(from: numberStr) {
                textField.text =  "\(textField.text ?? "")\(final)"
            }
                return false
        }
        return true
    }

不要忘记设置代理人:

yourTextField.delegat =自我

答案 4 :(得分:0)

我有一个更简单的字符串扩展解决方案:

extension String{
/// To convert Arabic / Persian numbers to English
/// - Returns: returns english number
func changeToEnglish()-> String{
    let numberFormatter = NumberFormatter()
    numberFormatter.locale = Locale(identifier: "EN")
    let engNumber = numberFormatter.number(from: self)
    return "\(engNumber!)"
}

/// To convert arabic or persian numbers to english
/// - Returns: returns Arabic number
func changeToArabic()-> String{
    let numberFormatter = NumberFormatter()
    numberFormatter.locale = Locale(identifier: "AR")
    let arabicNumber = numberFormatter.number(from: self)
    return "\(arabicNumber!)"
}