Ios-json parsing accuracy loss processing (NSString, Double, Float)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.