Hadiseh
Hadiseh

Reputation: 87

Sum Integer With String In Swift

I have one text field. My text field text is a number with currencyFormatter. My text field text is like "100,000". Now I want sum this textField text with 1000 but I can't. I Use currencyFormatter() Function like that self.textField.text = 100000.currencyFormatter()

My function is:

extension Int {
    func currencyFormatter() -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.maximumFractionDigits = 0

        if let result = formatter.string(from: NSNumber(value: self))
        {
            return result;
        }

        return String(self);
    } }

    func sum(){
        let firstValue = Int(txtAmount.text!)
        let secondValue = 1000
        if firstValue != nil {
            let outputValue = Int(firstValue! - secondValue)
            self.txtAmount.text = "\(outputValue)"
        }
        else{
            self.txtAmount.text = "\(firstValue!)"
        }       
    }

Upvotes: 0

Views: 489

Answers (2)

mistdon
mistdon

Reputation: 1893

Maybe you should learn how to use NumberFormatter.

Here you are the code

func sumStrAndDouble(str: String?, num: Double) -> String {
    guard let str = str else {
        return String(num)
    }
    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    let transferStr = formatter.number(from: str)
    let sum = (transferStr as? Double) ?? 0 + num
    let _res =  formatter2.string(from: NSNumber(value: sum))
    return _res ?? ""
}

let a = sumStrAndDouble(str: "100,100", num: 1000) // 100,100

For you, you can use like

let res = sumStrAndDouble(str: self.textField.text, num: 1000)

Upvotes: 0

Joakim Danielson
Joakim Danielson

Reputation: 52098

You should use the same instance of NumberFormatter to convert in both directions

So here is the formatter as you have already configured it

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 0

Then write a function that adds an int to a int represented as a string

func add(_ value: Int, to stringValue: String) -> Int {
    if let converted = formatter.number(from: stringValue) {
        return value + converted.intValue
    }

    return value // or throw an error or return nil...
}

Then use it like

if let textValue = self.txtAmount.text, !text.isEmpty {
    newValue = add(1000, to: textValue)
    self.txtAamount.text = formatter.string(from: NSNumber(value: newValue)) ?? ""
}

Upvotes: 1

Related Questions