search

Home  >  Q&A  >  body text

ios - json 解析float类型多出几位小数怎么处理?

后台返回float类型数据8.2,实际用AFN的json解析后得到8.1999999999怎么回事?该怎么处理啊?

高洛峰高洛峰2815 days ago1326

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-18 09:32:46

    Isn’t the returned string a string? id = 2747 is the basic data type. Let the background process it directly

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 09:32:46

    Try using NSNumber accept? Then, sometimes the type conversion does go wrong, and then you can try it again on the browser.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:32:46

    Thank you everyone, I have found a solution. When returning float or double type in the background, use NSDecimalNumber to deal with the problem of precision loss.
    Here I received it in string mode and directly added the NSString classification. The correction method is posted as follows:

    +(NSString )reviseString:(NSString )string{

    /* 直接传入精度丢失有问题的Double类型*/
    double conversionValue        = (double)[string floatValue];
    NSString *doubleString        = [NSString stringWithFormat:@"%lf", conversionValue];
    NSDecimalNumber *decNumber    = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];

    }

    The data returned in this way is the corrected precision data. Because of personal needs, it is converted into string type

    reply
    0
  • Cancelreply