json解析精度问题

Posted LiLM

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了json解析精度问题相关的知识,希望对你有一定的参考价值。

由于后台传过来的值是float或者double类型,解析之后作为对象放到字典或数组里面,被转成nsstring或者nsnumber会有一定的误差,很正常

解决办法,通过NSNumberFormatter,可以设置NSNumber输出的格式;

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];

 formatter.numberStyle = NSNumberFormatterDecimalStyle;

 NSString *string = [formatter stringFromNumber:[NSNumber numberWithInt:123.85999999999]];

 NSLog(@"Formatted number string:%@",string);

//枚举类型

typedef NS_ENUM(NSUInteger, NSNumberFormatterRoundingMode) {

    NSNumberFormatterRoundCeiling = kCFNumberFormatterRoundCeiling,

    NSNumberFormatterRoundFloor = kCFNumberFormatterRoundFloor,

    NSNumberFormatterRoundDown = kCFNumberFormatterRoundDown,

    NSNumberFormatterRoundUp = kCFNumberFormatterRoundUp,

    NSNumberFormatterRoundHalfEven = kCFNumberFormatterRoundHalfEven,

    NSNumberFormatterRoundHalfDown = kCFNumberFormatterRoundHalfDown,

    NSNumberFormatterRoundHalfUp = kCFNumberFormatterRoundHalfUp

};

 

NSNumberFormatterRoundCeiling = kCFNumberFormatterRoundCeiling,//四舍五入,直接输出124

    NSNumberFormatterRoundFloor = kCFNumberFormatterRoundFloor,//保留小数输出123.86

    NSNumberFormatterRoundDown = kCFNumberFormatterRoundDown,//加上了人民币标志

    NSNumberFormatterRoundUp = kCFNumberFormatterRoundUp,//百分号表示

    NSNumberFormatterRoundHalfEven = kCFNumberFormatterRoundHalfEven

    NSNumberFormatterRoundHalfDown = kCFNumberFormatterRoundHalfDown

    NSNumberFormatterRoundHalfUp = kCFNumberFormatterRoundHalfUp 

以上是关于json解析精度问题的主要内容,如果未能解决你的问题,请参考以下文章

ios 在json解析过程中浮点型字符串出现精度丢失问题

我无法从 JSON 解析正确的双精度

在 Flutter 和 Dart 中从 JSON 解析双精度值

关于json解析float数据精度的问题

iOS - Json解析精度丢失处理(NSString, Double, Float)

使用JSON.parse解析数量