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

问题描述 投票:0回答:4

我正在使用一种改变的方法来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
}
ios uitextfield swift3 nsnumberformatter uitextfielddelegate
4个回答
2
投票

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

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


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”

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


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

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.