iOS浮点数去掉小数点之后的0

我们在显示价格或者其他的单位时,可能会遇到这样的需求,如果给定一个浮点数显示小数点之后四位,但是要截取0

例如:7.0090,显示为7.009;2.0000,显示为2;5.0500,显示为5.05,总之就是将浮点数小数点有数字之后的0都给截取掉显示

代码如下:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *str = @"0.456560000000";
    NSString *str1 = @"1.0000";
    NSString *str2 = @"2.2000";
    NSString *str3 = @"3.0300";
    NSString *str4 = @"4.0040";
    NSString *str5 = @"5.0005";
    NSString *str6 = @"6.0006000000";
    NSString *str7 = @"7.00000700";
    NSLog(@"str----%@",[self removeFloatAllZeroByString:str]);
    NSLog(@"str1----%@",[self removeFloatAllZeroByString:str1]);
    NSLog(@"str2----%@",[self removeFloatAllZeroByString:str2]);
    NSLog(@"str3----%@",[self removeFloatAllZeroByString:str3]);
    NSLog(@"str4----%@",[self removeFloatAllZeroByString:str4]);
    NSLog(@"str5----%@",[self removeFloatAllZeroByString:str5]);
    NSLog(@"str6----%@",[self removeFloatAllZeroByString:str6]);
    NSLog(@"str7----%@",[self removeFloatAllZeroByString:str7]);
}

- (NSString*)removeFloatAllZeroByString:(NSString *)testNumber{
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(testNumber.floatValue)];
    return outNumber;
}

详细见图:

iOS浮点数去掉小数点之后的0_第1张图片

当然我们可以给字符串新增一个类别,然后将其提取在NSString类的扩展方法中,如下:

- (NSString*)removeFloatAllZero:(NSString*)string{
    
//    /*---------第一种方法-----------*/
//    NSString * testNumber = string;
//    NSString * s = nil;
//    NSInteger 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);
    
    
    /*---------第二种方法-----------*/
    NSString * testNumber = string;
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(testNumber.floatValue)];
    return outNumber;
}


你可能感兴趣的:(iOS-OC)