美文网首页
iOS 接口返回NSNumber类型处理,支持四舍五入

iOS 接口返回NSNumber类型处理,支持四舍五入

作者: SoaringHeart | 来源:发表于2018-07-20 17:46 被阅读120次

    本文原创,转载请加链接

    接口返回数据类型NSNumber如下
    84.430000000000007
    1.1799999999999999
    
    处理步骤:
    第一步:
    #import "NSNumberFormatter+Helper.h"
    NSNumberFormatter分类中实现
    + (NSNumberFormatter *)numWithIdentify:(NSString *)identify{
        // 版本2 ,使用当前线程字典来保存对象
        NSMutableDictionary *threadDic = [[NSThread currentThread] threadDictionary];
        NSNumberFormatter *formatter = [threadDic objectForKey:identify];
        if (!formatter) {
            formatter = [[NSNumberFormatter alloc]init];
            [threadDic setObject:formatter forKey:identify];
        }
        return formatter;
    }
    
    第二步:
    #import "NSNumber+Helper.h"
    NSNumberFormatter分类中实现
    
    -(NSString *)stringWithIdentify:(NSString *)identify{
        NSNumberFormatter *formatter = [NSNumberFormatter numWithIdentify:identify];
    //    DDLog(@"_%p_",formatter);//确保formatter为同一对象
        formatter.minimumIntegerDigits = 1;
        formatter.maximumFractionDigits = 2;
        formatter.roundingMode = NSNumberFormatterRoundFloor;
        NSString *string = [formatter stringFromNumber:self];
        return string;
    }
    
    //最终调用方法
    -(NSString *)BN_StringValue{
        return [self stringWithIdentify:@"四舍五入"];
        
    }
    ---
    举例(目前完美适应整数和double):
    if ([value isKindOfClass:[NSNumber class]]) {
          NSString *string = [(NSNumber *)value BN_StringValue];
    }
    Printing description of string:
    84.43
    Printing description of string:
    1.18
    
    

    相关文章

      网友评论

          本文标题:iOS 接口返回NSNumber类型处理,支持四舍五入

          本文链接:https://www.haomeiwen.com/subject/jnmqmftx.html