160309iOS 浮点数显示的问题。

先看一段代码

    CGFloat tempFloat = 3.05;
    NSString* tempStr = [NSString stringWithFormat:@"%.1f", tempFloat];
    NSLog(@"tempFloat = %@", tempStr);

这样打印出来的是3.0

    CGFloat tempFloat = 3.051;
    NSString* tempStr = [NSString stringWithFormat:@"%.1f", tempFloat];
    NSLog(@"tempFloat = %@", tempStr);
而这样打印出来的是3.1.为什么呢,原因ios采用的是四舍六入五凑偶的规则

这里“四”是指≤4 时舍去,"六"是指≥6时进上,"五"指的是根据5后面的数字来定,当5后有数时,舍5入1;当5后无有效数字时,需要分两种情况来讲:①5前为奇数,舍5入1;②5前为偶数,舍5不进。(0是偶数)

注意,CGFloat的用法。

typedef float CGFloat;//  32-bit 

typedef double CGFloat;// 64-bit 

    CGFloat tempFloat = 3.250000001;
    float tempFloat1 = 3.250000001;
    NSLog(@"tempFloat = %.1f, tempFloat1 = %.1f", tempFloat, tempFloat1);

tempFloat打印出来的是3.3而tempFoalt1是3.2,

tempFloat的精度超过9位,5后面有数时,舍5进入,得到的是3.2+0.1 3.3

tempFloat1的精度低于9位,5后面无有效数时,5前为偶数,舍5不进,故为3.2


致于为什么会出现这样的问题,可以看下一篇,float,double等精度丢失问题。http://blog.csdn.net/lmyuanhang/article/details/50836348

如果是货币等需要精确数计算的可以使用NSDecimalNumber进行计算,如

NSString *decimalNumberMutiplyWithString(NSString *multiplierValue,NSString *multiplicandValue)
{
     NSDecimalNumber *multiplierNumber = [NSDecimalNumber decimalNumberWithString:multiplierValue];
     NSDecimalNumber *multiplicandNumber = [NSDecimalNumber decimalNumberWithString:multiplicandValue];
     NSDecimalNumber *product = [multiplicandNumber decimalNumberByMultiplyingBy:multiplierNumber];
     return [product stringValue];
}
 
NSLog(@"%@",decimalNumberMutiplyWithString([NSString stringWithFormat:@"%f",a], [NSString stringWithFormat:@"%d",b]));

所以从服务器获取的浮点数时最好用字符串来表示,这样再用到的时候直接显示,就不会出现浮点数不精确,而与其他平台显示不一致的问题。如需计算可以使用NSDecimalNumber进行计算。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值