浮点数运算
两个浮点数直接运算可能产生的问题:
a.精度缺失问题
浮点数运算的最终解决方案( 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]));
//输出结果 999999.99
将float/double类型变量先转成NSDecimalNumber对象,然后进行各种加减乘除运算,除数不能为0,最后运算结果再取double的值,精度按自己需求取。
b.取小数点后几位会自动四舍五入的问题
解决方案(截取小数点后几位,并不四舍五入)
ini
-(NSString *)notRounding:(float)price afterPoint:(int)position{
NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
NSDecimalNumber *ouncesDecimal;
NSDecimalNumber *roundedOunces;
ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];
roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
[ouncesDecimal release];
return [NSString stringWithFormat:@"%@",roundedOunces];
}
参数介绍
price:需要处理的数字,
position:保留小数点第几位,
然后调用
ini
float s =0.126;
NSString *sb = [self notRounding:s afterPoint:2];
NSLog(@"sb = %@",sb);
输出结果为:sb = 0.12
接下来介绍NSDecimalNumberHandler
初始化时的关键参数:decimalNumberHandlerWithRoundingMode:NSRoundDown
,
NSRoundDown代表的就是 只舍不入。
scale的参数position代表保留小数点后几位。