iOS - Json解析精度丟失處理(NSString, Double, Float)

來源:互聯網
上載者:User

標籤:做了   nbsp   精度   ios   double   string   number   方法   重要   

開發中處理處理價格金額問題, 後台經常返回float類型, 列印或轉成NSString都會有精度丟失問題, 因此使用系統內建的NSDecimalNumber做處理, 能解決這問題:
經過測試其實系統NSDecimalNumber是對有問題值做了四捨五入處理


    ?    還有經過測試, 重要的事說三遍:?處理精度有關的資料請用double?處理精度有關的資料請用double?處理精度有關的資料請用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];
}
強烈建議 :
   有關浮點型資料,後台傳字串的格式,防止丟失精度。

iOS - Json解析精度丟失處理(NSString, Double, Float)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.