• NSNumber 和 NSString 转换


    直接上实例:

    什么目的呢?  // @98.9899999 ---> @"98.989999"

    让服务器返回的整数还是整数, 返回小数多了我们就只保留两位, 从模型上修改, 这个思想很重要,凡是引用到地方自己自动变,而不是每个地方都去修改,抛砖引玉,希望对各位有所帮助

    - (NSNumber *)dealNumber:(NSNumber *)sourceNumber

    {

        NSString *str = [sourceNumber description];

      

      NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^\d+\.\d{2}" options:NSRegularExpressionCaseInsensitive error:nil];

        

        NSArray *results = [regex matchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, str.length)];

        

        for (NSTextCheckingResult *result in results) {

            HMLog(@"%@", [str substringWithRange:result.range]);

        }

        

        // 小数点的位置

        NSUInteger dotIndex = [str rangeOfString:@"."].location;

        if (dotIndex != NSNotFound && str.length - dotIndex > 2) { // 小数超过2位

            str = [str substringToIndex:dotIndex + 3];

        }

        //有个NSNumberFormatter类,不常用,可以把num转变成string,而不用先变成 float,再转变成str,会有精度损失

        NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];

        return [fmt numberFromString:str];

    }

    - (void)setList_price:(NSNumber *)list_price

    {

        // @98.9899999 ---> @"98.989999"

        _list_price = [self dealNumber:list_price];

    }

    - (void)setCurrent_price:(NSNumber *)current_price

    {

        _current_price = [self dealNumber:current_price];

    }

  • 相关阅读:
    linux十九压缩解压
    linux第十八dd命令
    【51单片机】数据类型
    【博客园】
    【C++】简介与环境的搭建
    【树莓派】安装TeamViewer
    【树莓派】Makefile的编写
    【cJSON库】cJSON库的使用
    【树莓派】忘记系统用户密码,如何重置密码
    【树莓派】树莓派与PC机通信
  • 原文地址:https://www.cnblogs.com/BinZone/p/4375515.html
Copyright © 2020-2023  润新知