skip to Main Content

I am very new to Swift. I am making a simple calculator. But the thing is that I cannot create a thousands separator. In the code below, when entering the number in TextField1, I want to enter it automatically with a thousands separator. For example, when writing, it should be written as 100.000 instead of 100000.

import UIKit

class ViewController: UIViewController {
    @IBOutlet var myTextField3: UITextField!
    @IBOutlet var myTextField2: UITextField!
    @IBOutlet var myTextField1: UITextField!
    @IBOutlet var myLabel1: UILabel!
    @IBOutlet var myLabel2: UILabel!
    
    @IBAction func myButton1(_ sender: Any) {
        myLabel1.isHidden = false
        myLabel2.isHidden = false
        let anapara = Float(myTextField1.text!)
        let vade = Float(myTextField2.text!)
        let ay = Float(myTextField3.text!)
        
        let outputValue = Int(((anapara! / 100 * vade! * ay!) + anapara!) / ay!)
        let outputValue2 = Int((anapara! / 100 * vade! * ay!) + anapara!)

        let formattedOutputValue = outputValue.withSeparator
        let formattedOutputValue2 = outputValue2.withSeparator

        myLabel1.text = "Aylık (formattedOutputValue) TL"
        myLabel2.text = "Toplam Ödeme (formattedOutputValue2) TL"
    }
}

extension Numeric {
    var withSeparator: String {
        let formatter = NumberFormatter()
        formatter.groupingSeparator = "."
        formatter.numberStyle = .decimal
        return formatter.string(for: self) ?? ""
    }
}

2

Answers


  1. Create a new Swift project if you haven’t already.
    Open your ViewController.swift file.
    Import UIKit and create an instance of NumberFormatter in your ViewController class:

    import UIKit
    
    class ViewController: UIViewController {
    
    let numberFormatter = NumberFormatter()
    
    // ... other code ...
    }
    

    In your viewDidLoad() method, set up the NumberFormatter with your desired formatting options, such as decimal places and the thousands separator:

    override func viewDidLoad() {
    super.viewDidLoad()
    
    // Configure the NumberFormatter
    numberFormatter.numberStyle = .decimal
    numberFormatter.maximumFractionDigits = 2 // Set your desired decimal places
    numberFormatter.groupingSeparator = "," // Use a comma as the thousands   separator
    
    // ... other code ...
    }
    

    Implement a function to update the text field as the user types:

    @IBOutlet weak var inputTextField: UITextField! // Connect this to your input text field in the storyboard
    
      @IBAction func textFieldEditingChanged(_ sender: UITextField) {
       if let text = sender.text,
       let number = numberFormatter.number(from: text) {
        sender.text = numberFormatter.string(from: number)
      }
      }
    

    Connect the inputTextField outlet and the textFieldEditingChanged action in your storyboard. Select the text field, open the Connections Inspector, and connect the "Editing Changed" event to the textFieldEditingChanged action.

    Now, when the user types a number into the inputTextField, it will automatically format it with thousands separators and the specified decimal places. For example, if the user types "100000," it will display as "100,000."

    Remember to adjust the NumberFormatter settings, such as the number of decimal places, grouping separator character, and decimal separator, according to your specific requirements.

    Login or Signup to reply.
  2. I don’t know if there is a best approach.

    What you can try to do is:

    1. Listen all the text change with func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
    2. Split the text on the decimal and integer
    3. format the integer number with NumberFormatter
    4. concatenate booth number and update on textfield

    this code can have a lot of improves but does the work if I understood the problem right

    class ViewController: UIViewController {
    
        let formatter = NumberFormatter()
        let decimalSeparator = ","
        let groupingSeparator = "."
    
        @IBOutlet weak var textFieldExample: UITextField!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            formatter.numberStyle = .decimal
            formatter.groupingSeparator = groupingSeparator
            formatter.decimalSeparator = decimalSeparator
            formatter.groupingSize = 3
        }
    }
    
    extension ViewController: UITextFieldDelegate {
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
            guard let text = textField.text,
               let textRange = Range(range, in: text) else {
                return true
            }
    
            let updatedText = text.replacingCharacters(in: textRange,
                                                       with: string)
    
            let numberSplitted = updatedText.components(separatedBy: decimalSeparator)
            guard numberSplitted.first != nil,
                  let onlyDigits = numberSplitted.first?.digits,
                  let number = Int(onlyDigits) else {
                return true
            }
            var decimalNumber = ""
            let intergerNumber = formatter.string(from: NSNumber(value: number)) ?? "0"
    
            if numberSplitted.count > 1, let decimalValue = numberSplitted.last {
                decimalNumber = ",(decimalValue.digits)"
            }
    
            textField.text = String("(intergerNumber)(decimalNumber)")
    
            return false
        }
    }
    
    extension String {
        var digits: String {
            return components(separatedBy: CharacterSet.decimalDigits.inverted)
                .joined()
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search