Does NSJSONSerialization deserialize numbers as NSDecimalNumber?

后端 未结 4 2074
甜味超标
甜味超标 2021-02-08 03:37

Take the following piece of code:

NSError *error;
NSString *myJSONString = @\"{ \\\"foo\\\" : 0.1}\";
NSData *jsonData = [myJSONString dataUsingEncoding:NSUTF8St         


        
4条回答
  •  无人共我
    2021-02-08 04:11

    NSJSONSerialization (and JSONSerialization in Swift) follow the general pattern:

    1. If a number has only an integer part (no decimal or exponent), attempt to parse it as a long long. If that doesn't overflow, return an NSNumber with long long.
    2. Attempt to parse a double with strtod_l. If it doesn't overflow, return an NSNumber with double.
    3. In all other cases, attempt to use NSDecimalNumber which supports a much larger range of values, specifically a mantissa up to 38 digits and exponent between -128...127.

    If you look at other examples people have posted you can see that when the value exceeds the range or precision of a double you get an NSDecimalNumber back.

提交回复
热议问题