Is there a way to append data to user input data?

I have two text field that require numeric user input.


At the moment my code accepts only a single decimal point and two digits after the decimal point. No problems with that. The issue I would like to address is this: If the user only enters '125' or '125.' and taps out of the text field, I would like for the text field to show '125.00' in both cases. So this will involve appending either '.00' or '00' to match the users data input.


If anyone can shed some light on this I would be most grateful.


Thanks!

Accepted Reply

get the label in s

convert to Double


format :


if let x = Double(s)  {   // check it's a numeric value
                let formatter = NSNumberFormatter()
                formatter.minimumFractionDigits = 2
                formatter.maximumFractionDigits = 2
               let myString = formatter.stringFromNumber(x)
}


load the textField with myString

Replies

get the label in s

convert to Double


format :


if let x = Double(s)  {   // check it's a numeric value
                let formatter = NSNumberFormatter()
                formatter.minimumFractionDigits = 2
                formatter.maximumFractionDigits = 2
               let myString = formatter.stringFromNumber(x)
}


load the textField with myString

You make it look so easy. LOL!


All of the data is numerical because I'm employing the number and decimal keypads so the user cannot enter alph chars. Your code is precisely what I needed.


I sincerely appreciate your help.

Either you use a NumberFormatter directly on the text field, or you parse the string and write back the formatted result with NumberFormatter.

The relevant fields to set on the NumberFormatter are:

formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.usesGroupingSeparator = false


For example, if you do it manually:


let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.usesGroupingSeparator = false
if let text = textField.text, let n = formatter.number(from: text) {
    textField.text = formatter.string(from: n)
}

Your input bounds assumptions may want to take external keyboards and pasting into account.

Thanks for your post.


I did take that into account, but the app in question is a gratutity calculator and I don't think a user would copy/paste their check data into the text fields primarily because the information is on a paper receipt. However, just to cover my six, I could be completely wrong in this regard.😕

Thanks for your post and the code.


I will take a good look at your code suggestion. I hope I will be able to make this work with the code I am currently using, which is (in part):


func textField(textFieldToChange: UITextField,
                    shouldChangeCharactersInRange range: NSRange,
                        replacementString string: String) -> Bool {
   
        if textFieldToChange == foodnDrinkTextField {
           
            let textFieldString = foodnDrinkTextField.text! as NSString
            let newString = textFieldString.stringByReplacingCharactersInRange(range, withString:string)
            let floatRegEx = "^([0-9]+)?(\\.([0-9]{1,2})?)?$" / 
            let floatExPredicate = NSPredicate(format:"SELF MATCHES %@", floatRegEx)
            return floatExPredicate.evaluateWithObject(newString)
           
        } else if textFieldToChange == taxTextField {
          .
          .
          .
        }
        return true
}


I will know more later tonight on this.


Thanks again for your help.

let floatRegEx = "^([0-9]+)?(\\.([0-9]{1,2})?)?$"

You do realise that a lot of European countries use comma (

,
) for separating the fractional part of decimals, right? So, how you write 1234.56 Euros depends on the user’s locale:
  • Ireland — €1,234.56

  • France — 1 234,56 €

  • Germany — 1.234,56 €

ahltorp suggested approach (NumberFormatter) will take care of this for you.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

@Claude31

@ahltorp

@*****

@eskimo


I just want to say Thank You! again to all who helped me with my formatting problem. I have since taken a hard look at NSNumberFormatter() and have worked out a lot of possibilities that this provides. While my demo app works great, I have another issue that I will address in another thread.


Thanks again!

I forgot to add in my last post that the use of NSNumberFormatter() also solved my orginal problem which was the addition of '.00' or '00' to the user input. That solved a big problem for me.


The use of NSNumberFormatter() is invaluable IMO.


I sincerely appreciate the help that everyone provided me.

@ahltorp

@eskimo


I am revisiting this thread because I am upgrading my app to Swift 4. I am not "comfortable" with the NumberFormatter / Predicate methods that I am currently using. That said, I decided to refactor all of this code as best I can with what knowledge I have.


Bottom line is this: I took your code and was amazed that it did in fact append either ".00" or "00" if the user entered "123" or "123." I do not profess to totally understand how it does that, but I will spend as much time as necessary to figure out how this code does what it does.


I am also taking to heart eskimo's comments about number separator's used by various locales, which my current code was not able to adapt to. The new changes should improve all of that functionality.


Thanks to all of you for your astute comments and code examples.


I am much wiser now and very grateful for all of your help.