在iOS开发中,进场遇到货币价格相关的计算,这是我们需要注意计算精度的问题。使用float类型运算,经常出现误差,为了解决这个问题我们使用NSDecimalNumber,下面通过例子的形式说明一下:
运算方法:
+ (void)test1
{
//不进行四舍五入
NSDecimalNumber *number1 = [NSDecimalNumber decimalNumberWithString:@"3.155"];
NSDecimalNumber *number2 = [NSDecimalNumber decimalNumberWithString:@"6.1"];
//加法
NSDecimalNumber * addNum = [number1 decimalNumberByAdding:number2];
NSLog(@"11------->>>> num=%@",addNum);
//进行四舍五入
// NSRoundUp 属性使所有的操作算到最接近的位置,其他的进位选项是 NSRoundPlain,NSRoundDown 和 NSRoundBankers ,他们被定义在NSRoundingMode,scale参数定义了结果值保留的小数位的数量,其余的参数给所有的操作定义了一场处理行为。
//scale 四舍五入,舍入位数
NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
addNum = [number1 decimalNumberByAdding:number2 withBehavior:roundUp];
NSLog(@"11------->>>> num=%@",addNum);
//减法
NSDecimalNumber * subtractNum = [number1 decimalNumberByAdding:number2];
NSLog(@"22------->>>> num=%@",subtractNum);
//进行四舍五入
subtractNum = [number1 decimalNumberBySubtracting:number2 withBehavior:roundUp];
NSLog(@"22------->>>> num=%@",subtractNum);
//乘法
NSDecimalNumber * multiplyNum = [number1 decimalNumberByMultiplyingBy:number2];
NSLog(@"33------->>>> num=%@",multiplyNum);
//进行四舍五入
multiplyNum = [number1 decimalNumberByMultiplyingBy:number2 withBehavior:roundUp];
NSLog(@"33------->>>> num=%@",multiplyNum);
//除法
NSDecimalNumber * divideNum = [number1 decimalNumberByDividingBy:number2];
NSLog(@"44------->>>> num=%@",divideNum);
divideNum = [number1 decimalNumberByDividingBy:number2 withBehavior:roundUp];
NSLog(@"44------->>>> num=%@",divideNum);
}