OC remove the extra 0 after the decimal point, not limited by the number of digits

//Remove the extra 0 after the decimal point

- (NSString *)removeRedundantZeroOfPointAfter:(NSString *)string

{

    

    NSArray *stringArr = [string componentsSeparatedByString:@"."];

    NSString *resultNum = @"0";

    

    if (stringArr.count > 1) {

        NSString *lastStr = stringArr.lastObject;

        NSArray *lastArr = [self subStringWithNoSpace:lastStr];

        for (NSInteger i = lastArr.count - 1; -1 < i; i--) {

            if (![lastArr[i] isEqual:@"0"]) {

                NSString *totalStr = lastArr[0];

                if (i == 0) {

                    resultNum = [NSString stringWithFormat:@"%@.%@", stringArr.firstObject, totalStr];

                }else {

                    for (NSUInteger j = 1; j <= i; j++) {

                        NSString *unitStr = lastArr[j];

                        totalStr = [totalStr stringByAppendingString:unitStr];

                    }

                    resultNum = [NSString stringWithFormat:@"%@.%@", stringArr.firstObject, totalStr];

                }

                break;

            }

            

            if (i == 0) {

                resultNum = stringArr.firstObject;

            }

        }

        

        return resultNum;

    }else

        resultNum = stringArr.firstObject;

        return resultNum;

    

}

 

 

//Split the string without the separator (divide the string into a character array)

- (NSArray *)subStringWithNoSpace:(NSString *)text

{

    NSMutableArray *textArray = @[].mutableCopy;

    for (NSInteger i = 0; i < text.length; i++) {

        NSString *str = [text substringToIndex:1];

        text = [text substringFromIndex:1];

        i = 0;

        [textArray addObject:str];

        if (text.length == 1) {

            [textArray addObject:text];

        }

    }

 

    return textArray;

}

Guess you like

Origin blog.csdn.net/niumanxx/article/details/81745168