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
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:
In your viewDidLoad() method, set up the NumberFormatter with your desired formatting options, such as decimal places and the thousands separator:
Implement a function to update the text field as the user types:
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.
I don’t know if there is a best approach.
What you can try to do is:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool
NumberFormatter
this code can have a lot of improves but does the work if I understood the problem right