iOS项目double、float精度丢失解决办法
描述
在iOS项目中老是遇到double、float精度丢失的问题
PS:
NSString * jsonStr = @"{\"9.70\":9.70,\"67.10\":67.10, \"90.10\":90.10, \"97.40\":97.40, \"99.40\":99.40}";
NSData * jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"json:%@",json);
结果:
json:{
"67.10" = "67.09999999999999";
"9.70" = "9.699999999999999";
"90.10" = "90.09999999999999";
"97.40" = "97.40000000000001";
"99.40" = "99.40000000000001";
}
解决方案
-
1、接口处理,返回为String类型;
-
2、使用
NSDecimalNumber
;double downDecimalPlaces(double origin, short scale){ /* roundingMode 要使用的舍入模式,有四种值: NSRoundPlain, 四舍五入 NSRoundDown, 只舍不入 NSRoundUp, 只入不舍 NSRoundBankers 四舍六入, 中间值时, 取最近的,保持保留最后一位为偶数 scale 结果保留几位小数 raiseOnExactness 发生精确错误时是否抛出异常,一般为NO raiseOnOverflow 发生溢出错误时是否抛出异常,一般为NO raiseOnUnderflow 发生不足错误时是否抛出异常,一般为NO raiseOnDivideByZero 被0除时是否抛出异常,一般为YES */ NSDecimalNumberHandler * handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:scale raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES]; NSDecimalNumber * decimal = [[NSDecimalNumber alloc] initWithDouble:origin]; NSDecimalNumber *outDecimal = [decimal decimalNumberByRoundingAccordingToBehavior:handler]; NSLog(@"=============origin%lf ========midfield%@ %lf",origin,outDecimal.stringValue,outDecimal.stringValue.doubleValue); return [outDecimal doubleValue]; };
-
使用
NSNumber
;NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init]; numberFormatter.numberStyle = NSNumberFormatterDecimalStyle; numberFormatter.minimumFractionDigits = 2;//最小小数位数 numberFormatter.maximumFractionDigits = 2;//最大小数位数 [numberFormatter stringFromNumber:number];