将逗号添加到数字值作为UITextField中的用户类型

时间:2016-12-16 06:22:31

标签: ios uitextfield swift3 nsnumberformatter uitextfielddelegate

我正在使用更改的方法this,我想在用户输入数字时格式化UITextField。就像在我想要的数字是实时格式化。我希望将1000改为1,000,50000到50,000等等。

我的问题是我的UITextField值未按预期更新。例如,当我在UITextField中键入50000时,结果将返回为5,0000而不是50,000。这是我的代码:

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
}

4 个答案:

答案 0 :(得分:2)

shouldChangeCharactersIn的规则编号1 - 如果为文本字段的text属性分配值,则必须返回false。返回true告诉文本字段对您已修改的文本进行原始更改。那不是你想要的。

您的代码中还有另一个主要缺陷。它不适用于使用其他方法格式化较大数字的语言环境。并非所有语言环境都使用逗号作为组分隔符。

答案 1 :(得分:1)

尝试使用 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)

它会打印出类似= " $ 9,999.99"

的值

您还可以根据需要设置区域设置

答案 2 :(得分: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

答案 3 :(得分:0)

使用货币样式代替使用小数样式。如果不需要,还可以设置currencySymbol空字符串。另外,请确保将您的设备区域选择为印度,否则它将在3位数字(而不是2位数字)之后添加逗号。

 -(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;
}