Processing price in the development of the problem, the background often return to float type, printing or turning into nsstring will have the problem of precision loss, so use the system's own nsdecimalnumber to do processing, can solve the problem:
After testing the system Nsdecimalnumber is the problem of the value of the rounding process
? And the test, the important thing to say three times:? Processing accuracy related data please use double? data related to processing accuracy please double
float testdouble = [jsondict[@ "Body"][@ "Amount"] floatvalue]; There is a problem 90.989999999999994
NSString *convertstring = decimalnumberwithstring ([jsondict[@ "Body"][@ "Amount"] stringvalue]);
NSLog (@ "%@", convertstring);
Testdouble Value Original value & Nsdecimalnumber after processing after printing the value
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
I wrote a method to deal with it:
/** Direct incoming precision loss of problematic double type */
NSString *decimalnumberwithdouble (double conversionvalue) {
NSString *doublestring = [NSString stringwithformat:@ "%lf", Conversionvalue];
Nsdecimalnumber *decnumber = [Nsdecimalnumber decimalnumberwithstring:doublestring];
return [Decnumber StringValue];
}
It is strongly recommended that:
For floating-point data, the format of the background string prevents loss of precision.
Ios-json parsing accuracy loss processing (NSString, Double, Float)