根据正则去掉小数点后多余的0,但是不起作用,望指导



 - (void)display{
    /**
     *  方法1(正则表达式)
     */
    NSString *regexZero = @"[0]$";
    NSString *regexDot = @"[.]$";
    NSPredicate *predZero = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexZero];
    NSPredicate *predDot = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexDot];
    while ([predZero evaluateWithObject:_numTemp] || [predDot evaluateWithObject:_numTemp]) {
        _numTemp = [_numTemp substringToIndex:_numTemp.length - 1];
    }

    /**
     *  方法2
     */
//    while ([[_numTemp substringFromIndex:_numTemp.length - 1] isEqualToString:@"0"] || [[_numTemp substringFromIndex:_numTemp.length - 1] isEqualToString:@"."]) {
//        _numTemp = [_numTemp substringToIndex:_numTemp.length - 1];
//    }


    [self.numDisplay setText:[NSString stringWithFormat:@"%@",_numTemp]];
}

ios objective-c swift

飒飒de枫 10 years, 3 months ago

你的这个写法,运算起来相对会低效一些,我提供两个方法你可以参考一下,像这样的情况,最好是封装成 Category

这个你可以这样:


 NSString * testNumber = @"3.1400000";
    NSString * s = nil;
    int offset = testNumber.length - 1;
    while (offset)
    {
        s = [testNumber substringWithRange:NSMakeRange(offset, 1)];
        if ([s isEqualToString:@"0"] || [s isEqualToString:@"."])
        {
            offset--;
        }
        else
        {
            break;
        }
    }
    NSString * outNumber = [testNumber substringToIndex:offset+1];
    NSLog(@"%@", outNumber);

还可以这样,先将字符串转成 double float 再格式化输出。


 NSString * testNumber = @"3.14000000";
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(testNumber.floatValue)];
    NSLog(@"%@", outNumber);

如果是限定一些格式的显示,最好是在服务器端处理好。

开着飞机打飞机 answered 10 years, 3 months ago

Your Answer