开发中处理处理价格金额问题, 后台经常返回float类型, 打印或转成NSString都会有精度丢失问题, 因此使用系统自带的NSDecimalNumber做处理, 能解决这问题:
经过测试其实系统NSDecimalNumber是对有问题值做了四舍五入处理


    •    还有经过测试, 重要的事说三遍:
处理精度有关的数据请用double
处理精度有关的数据请用double
处理精度有关的数据请用double
    float testDouble = [jsonDict[@"Body"][@"Amount"] floatValue]; //有问题 90.989999999999994
    NSString *convertString = decimalNumberWithString([jsonDict[@"Body"][@"Amount"] stringValue]);
    NSLog(@"%@", convertString);
       testDouble的值     原始值& NSDecimalNumber处理后打印后的值
//    99.489999999999994 99.49
//    99.989999999999994 99.99
//    90                 90.00
//    90.090000000000003 90.09
//    90.189999999999998 90.19
//    90.290000000000006 90.29
//    90.39              90.39
//    90.489999999999994 90.49
//    90.590000000000003 90.59
//    90.689999999999998 90.69
//    90.790000000000006 90.79
//    90.89              90.89
//    90.989999999999994 90.99


对此自己写了个方法处理 :
/** 直接传入精度丢失有问题的Double类型*/
NSString *decimalNumberWithDouble(double conversionValue){
    NSString *doubleString        = [NSString stringWithFormat:@"%lf", conversionValue];
    NSDecimalNumber *decNumber    = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}
强烈建议 :
   有关浮点型数据,后台传字符串的格式,防止丢失精度。

相关文章:

  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2022-12-23
  • 2021-08-27
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-04
  • 2021-11-01
  • 2021-10-10
  • 2021-10-13
  • 2021-11-18
  • 2021-09-08
相关资源
相似解决方案