開發(fā)中處理處理價格金額問題, 后臺經(jīng)常返回float類型, 打印或轉(zhuǎn)成NSString都會有精度丟失問題, 因此使用系統(tǒng)自帶的NSDecimalNumber做處理, 能解決這問題:
經(jīng)過測試其實系統(tǒng)
NSDecimalNumber是對有問題值做了四舍五入處理
- 還有經(jīng)過測試, 重要的事說三遍:
處理精度有關(guān)的數(shù)據(jù)請用double
處理精度有關(guān)的數(shù)據(jù)請用double
處理精度有關(guān)的數(shù)據(jù)請用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];
}
強烈建議 :
有關(guān)浮點型數(shù)據(jù),后臺傳字符串的格式,防止丟失精度。