開發(fā)遇到的一個坑。在與后臺交互的時候,協(xié)議規(guī)定的數(shù)據(jù)類型是浮點型歉糜,這就要求我們將用戶輸入的字符串轉化為float類型。但是在轉化過程中會出現(xiàn)失真的情況望众。
其實float與str互轉會出現(xiàn)失真的情況匪补,原因很簡單。這是因為浮點數(shù)的存儲方式的緣故烂翰。
NSLog(@"%f",[@"20.5" floatValue]);
NSLog(@"%f",[@"20.7" floatValue]);
NSLog(@"%f",[@"20.75" floatValue]);
NSLog(@"%f",[@"20.76" floatValue]);
NSLog(@"%f",[@"20.875" floatValue]);
NSLog(@"%f",[@"20.878" floatValue]);
NSLog(@"%f",[@"20.09375" floatValue]);
NSLog(@"%f",[@"20.09335" floatValue]);
NSLog(@"%f",[@"20.546875" floatValue]);
NSLog(@"%f",[@"20.546878" floatValue]);
2018-08-25 11:21:58.833098+0800 floatValueDistortion[3523:408253] 20.500000
2018-08-25 11:21:58.833285+0800 floatValueDistortion[3523:408253] 20.700001
2018-08-25 11:21:58.833401+0800 floatValueDistortion[3523:408253] 20.750000
2018-08-25 11:21:58.833520+0800 floatValueDistortion[3523:408253] 20.760000
2018-08-25 11:21:58.833623+0800 floatValueDistortion[3523:408253] 20.875000
2018-08-25 11:21:58.834162+0800 floatValueDistortion[3523:408253] 20.878000
2018-08-25 11:21:58.834477+0800 floatValueDistortion[3523:408253] 20.093750
2018-08-25 11:21:58.834636+0800 floatValueDistortion[3523:408253] 20.093349
2018-08-25 11:21:58.834784+0800 floatValueDistortion[3523:408253] 20.546875
2018-08-25 11:21:58.834978+0800 floatValueDistortion[3523:408253] 20.546879
在回顧了浮點數(shù)的存儲方式之后夯缺,和后臺商議使用更改數(shù)據(jù)類型為字符串進行傳輸,問題就解決了甘耿。但是如果要用輸入的類型進行計算呢踊兜?這個時候問題就避不開了。
其實蘋果已有線程的API是可以支持的佳恬。NSDecimalNumber看定義就可以發(fā)現(xiàn)捏境,不同于浮點數(shù)的存儲,他是十進制的毁葱。同時也可以定制精度的取正類型:向上取正垫言、向下去正、四舍五入等倾剿。相對與浮點類型的計算骏掀,NSDecimalNumber提供了更加精準的計算。
NSDecimalNumber
An object for representing and performing arithmetic on base-10 numbers.
- (void)caculateTest
{
NSString * floatStr1 =@"14.326";
NSString * floatStr2 =@"7.54";
NSDecimalNumber * num1 = [NSDecimalNumber decimalNumberWithString:floatStr1];
NSDecimalNumber * num2 = [NSDecimalNumber decimalNumberWithString:floatStr2];
NSDecimalNumber *num3 = [num1 decimalNumberByAdding:num2];
CGFloat float3 = [floatStr1 floatValue] + [floatStr2 floatValue];
NSLog(@"%@,%f",num3,float3);
NSDecimalNumber *num4 = [num1 decimalNumberBySubtracting:num2];
CGFloat float4 = [floatStr1 floatValue] - [floatStr2 floatValue];
NSLog(@"%@,%f",num4,float4);
NSDecimalNumber *num5 = [num1 decimalNumberByMultiplyingBy:num2];
CGFloat float5 = [floatStr1 floatValue] * [floatStr2 floatValue];
NSLog(@"%@,%f",num5,float5);
NSDecimalNumber *num6 = [num1 decimalNumberByDividingBy:num2];
CGFloat float6 = [floatStr1 floatValue] / [floatStr2 floatValue];
NSLog(@"%@,%f",num6,float6);
}
floatValueDistortion[3897:448522] 21.866,21.866001
2018-08-25 12:31:09.503985+0800 floatValueDistortion[3897:448522] 6.786,6.786000
2018-08-25 12:31:09.504800+0800 floatValueDistortion[3897:448522] 108.01804,108.018044
2018-08-25 12:31:09.504993+0800 floatValueDistortion[3897:448522] 1.9,1.900000