0

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!)"
        }       
    }
1
  • 1
    Use NumberFormatter to parse the number first. Commented Mar 10, 2020 at 9:32

2 Answers 2

1

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)) ?? ""
}
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.