iOS NSNumber 的属性 stringValue 造成的偏差

0x00 上代码

    NSNumber *obj = @(99999.99);
    NSLog(@"%@",obj.stringValue); // 99999.99000000001
    
    obj = @(99999.98);
    NSLog(@"%@",obj.stringValue); // 99999.98
    
    obj = @(99999.999);
    NSLog(@"%@",obj.stringValue); // 99999.999
    
    obj = @(99999.998);
    NSLog(@"%@",obj.stringValue); // 99999.99800000001

结论:不要用 NSNumberstringValue 来格式化数字,否则会出现显示误差的问题。


0x01 正确姿势

    CGFloat obj = 99999.99;
    NSLog(@"%@",[NSString stringWithFormat:@"%.6lf", obj]); // 99999.990000
    
    obj = 99999.98;
    NSLog(@"%@",[NSString stringWithFormat:@"%.6lf", obj]); // 99999.980000
    
    obj = 99999.999;
    NSLog(@"%@",[NSString stringWithFormat:@"%.6lf", obj]); // 99999.999000
    
    obj = 99999.998;
    NSLog(@"%@",[NSString stringWithFormat:@"%.6lf", obj]); // 99999.998000

一款小巧的在线编译器

请添加图片描述


猜你喜欢

转载自blog.csdn.net/xjh093/article/details/119377928
今日推荐