先看一段代码
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进行计算。