0

I am using an altered method to this where I want to format a UITextField as the user is typing in the number. As in I want the number being live-formatted. I am looking to change 1000 to 1,000, 50000 to 50,000 and so on.

My issue is that my UITextField values are not updating as expected. For instance, when I type in 50000 in the UITextField the result is coming back as 5,0000 instead of 50,000. Here is my code:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    //check if any numbers in the textField exist before editing
    guard let textFieldHasText = (textField.text), !textFieldHasText.isEmpty else {
        //early escape if nil
        return true
    }

    let formatter = NumberFormatter()
    formatter.numberStyle = NumberFormatter.Style.decimal

    //remove any existing commas
    let textRemovedCommma = textFieldHasText.replacingOccurrences(of: ",", with: "")

    //update the textField with commas
    let formattedNum = formatter.string(from: NSNumber(value: Int(textRemovedCommma)!))
    textField.text = formattedNum
    return true
}
Community
  • 1
  • 1
Sami
  • 579
  • 5
  • 25
  • http://stackoverflow.com/questions/24115141/swift-converting-string-to-int/34294660?s=1|0.1034#34294660 – Leo Dabus Dec 16 '16 at 06:28

4 Answers4

3

Rule number 1 of shouldChangeCharactersIn - If you assign a value to the text field's text property you must return false. Returning true tells the text field to make the original change to the text that you have already modified. That is not what you want.

You have one other major flaw in your code. It won't work in locales that use other ways to format larger numbers. Not all locales use a comma as the group separator.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Thanks - I didn't realize I was using the true/false return incorrectly. And thanks for catching the locale issue. I'll try to fix this and I will report back ! – Sami Dec 17 '16 at 19:18
1

Try using NSNumberFormatter.

var currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
// localize to your grouping and decimal separator
currencyFormatter.locale = NSLocale.current
var priceString = currencyFormatter.string(from: 9999.99)

It will print value like = "$9,999.99"

You can also set the Locale as per your need.

Wolverine
  • 4,264
  • 1
  • 27
  • 49
1
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
let textRemovedCommma = textField.text?.replacingOccurrences(of: ",", with: "")
let formattedNum = formatter.string(from: NSNumber(value: Int(textRemovedCommma!)!))
textField.text = formattedNum
  • Hey there! While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – Wing Nov 21 '17 at 12:37
0

Instead of using decimal style use currency style. Also set currencySymbol empty string if you don't need it. Also make sure your device region is selected as India other wise it will add commas after 3 digit instead of 2 digits.

 -(NSString*)addingCommasToFloatValueString:(NSString *)rupeeValue 
{
NSNumber *aNumber = [NSNumber numberWithDouble:[rupeeValue   doubleValue]];
NSNumberFormatter *aFormatter = [NSNumberFormatter new];
[aFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[aFormatter setCurrencySymbol:@""];
[aFormatter setMinimumFractionDigits:0];
[aFormatter setMaximumFractionDigits:2];
NSString *formattedNumber = [aFormatter stringFromNumber:aNumber];
return formattedNumber;
}