好用的金额字符串处理iOS

最近又在搞金额,有时候会有类似0.0100,有时候会有类似3.98000001样子,这时候需要把金额保留两位有效数字,有时候需要保留一位有效数字,有时候金额返回整数,通过这个方法可以直接恢复到你想要的样子,如下:

-(NSString *)stringByYouWantWithOriginString:(NSString *)originString{
    NSString *MM = @"";
    if ([originString containsString:@"."]) {
        NSArray *array_XString = [originString componentsSeparatedByString:@"."];
        NSString *string_XLast = array_XString.lastObject;
        if (string_XLast.length == 1 ) {
            MM = [NSString stringWithFormat:@"%.1f",[originString floatValue]];
        }else if (string_XLast.length >=2){
            MM = [NSString stringWithFormat:@"%.2f",[originString floatValue]];
        }
        if (string_XLast.length >=2){
            if ([MM hasSuffix:@"00"]) {
                MM = [NSString stringWithFormat:@"%.0f" , [MM floatValue]];
            }else if ([MM hasSuffix:@"0"]){
                MM = [NSString stringWithFormat:@"%.1f" , [MM floatValue]];
            }
        }else if (string_XLast.length ==1 ){
            if ([MM hasSuffix:@"0"]) {
                MM =[NSString stringWithFormat:@"%.0f" , [MM floatValue]];
            }
        }
    }else{
        MM =originString;
    }
    if ([MM hasSuffix:@".00"]) {
        MM = [NSString stringWithFormat:@"%.0f",[MM floatValue]];
    }
    return MM;
}

推荐阅读更多精彩内容