在开发中,遇到和货币价格计算相关的问题时,需要注意计算的精度。在使用float类型运算,会出现精度丢失问题。可使用NSDecimalNumber。
NSDecimalNumber *a = [NSDecimalNumber decimalNumberWithString:@"93.891"];
NSDecimalNumber *b = [NSDecimalNumber decimalNumberWithString:@"8.764"];
1.加法
//不进行四舍五入
NSDecimalNumber *num = [a decimalNumberByAdding:b];
//四舍五入
//NSRoundUp属性使所有的操作算到最近的位置,其他的进位选项是NSRoundPlain, NSRoundDown, 和 NSRoundBankers,它们都被定义在NSRoundingMode,scale参数定义了结果值保留的小数位的数量,其余的参数给所有的操作定义了异常处理行为.
NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
NSDecimalNumber *num = [a decimalNumberByAdding:b withBehavior:roundUp];
2.减法
NSDecimalNumber *num = [a decimalNumberBySubtracting:b];
3.乘法
NSDecimalNumber *num = [a decimalNumberByMultiplyingBy:b];
3.除法
NSDecimalNumber *num = [a decimalNumberByDividingBy:b];