NSNumberFormatter千位分离器

时间:2016-11-09 08:48:40

标签: ios objective-c xcode nsnumber nsnumberformatter

我想创造一千个分隔符。当我在textfield中键入数字时,它可以正常工作。但是,当我从textfield中删除一个数字时,我无法工作。

键入时的屏幕截图:

testasdsadasdas

从文本字段中删除数字时的屏幕截图:

enter image description here

但是我希望有这样的数字:121.132,你能帮我解决这个问题吗?

代码:

template <typename Base>
class HeavyWeightClassIWantToTestGeneric: public Base
{
public:
    // ...

    void MethodThatNeedsTest()
    {
        //calc some values
        int result = this->GetValue(); // use `this->` for dependent name
        //do some other stuff
    }
};

// For production
using HeavyWeightClassProduction = HeavyWeightClassIWantToTestGeneric<UntouchableBase>;

// For Test
using HeavyWeightTest = HeavyWeightClassIWantToTestGeneric<TestBase>;

1 个答案:

答案 0 :(得分:0)

尝试以下任何解决方案:

解决方案1 ​​

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSNumberFormatter *nf = [[NSNumberFormatter alloc] init] ;
    [nf setGroupingSize:3];
    [nf setCurrencyGroupingSeparator:@"."];
    [nf setUsesGroupingSeparator:YES];
    // you should create a string from number
    NSNumber *n = [NSNumber numberWithLong: 100000000];
    NSString *str = [nf stringFromNumber: n];
    textField.text = str;
    NSLog(@"My number: %@", str);
    return true;
}

解决方案2

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
           NSString *strTest = [NSString stringWithFormat:@"%@,%@",textField.text,string];
            NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init] ;
            [formatter setGroupingSeparator:@"."];
            [formatter setGroupingSize:2];
            [formatter setUsesGroupingSeparator:YES];
            [formatter setSecondaryGroupingSize:3];
            NSString *num = strTest ;
            if(![num isEqualToString:@""])
            {
                num= [num stringByReplacingOccurrencesOfString:@"." withString:@""];
                NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];

                _textField.text=str;

            }

        return true;
    }