在客户端处理金额的时候,通常会涉及小数点后两位有效数字,如果使用float和double的时候都会因为精度导致误差的产生,不满足金额对准确度的需求。苹果为我们提供了NSDecimalNumber的API来处理货币计算的问题。
NSDecimalNumberHandler:
/**
数值格式设置
RoundingMode: 舍入模式,有四种值:NSRoundUp(只入不舍), NSRoundDown(只舍不入), NSRoundPlain(四舍五入), NSRoundBankers(四舍六入, 中间值时, 取最近的,保持保留最后一位为偶数)
scale: 保留几位小数
raiseOnExactness: 发生精确错误时是否抛出异常,一般为NO
raiseOnOverflow: 发生溢出错误时是否抛出异常,一般为NO
raiseOnUnderflow: 发生不足错误时是否抛出异常,一般为NO
raiseOnDivideByZero: 除数是0时是否抛出异常,一般为YES
*/
NSDecimalNumberHandler *decimalNumberHandler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
NSDecimalNumber:NSDecimalNumber是NSNumber的子类,是苹果针对浮点型计算时存在精度误差的问题而提供的一个类。
/**
Mantissa: 无符号长整型数值
exponent: 指数(几次方)
isNegative:是否是负数
result = Mantissa * 10^exponent
*/
NSDecimalNumber *dn1 = [NSDecimalNumber decimalNumberWithMantissa:36868 exponent:3 isNegative:NO];//36868000
NSDecimalNumber *dn2 = [NSDecimalNumber decimalNumberWithMantissa:36868 exponent:-3 isNegative:YES];//-36.868
NSLog(@"dn1 = %@,dn2 = %@",dn1,dn2);
//NSDecimalNumber 的使用。NSDecimalNumber是进行数值计算的对象,所有的加减乘除,幂运算等。
//123456789987654321.68 + 0.22 然后四舍五入
NSDecimalNumber *oneDecimalNumber = [[NSDecimalNumber alloc] initWithString:@"123456789987654321.68"];
NSDecimalNumber *twoDecimalNumber = [[NSDecimalNumber alloc] initWithString:@"0.22"];
//加
NSDecimalNumber *addRes = [oneDecimalNumber decimalNumberByAdding:twoDecimalNumber withBehavior:decimalNumberHandler];
//减
NSDecimalNumber *subtractRes = [oneDecimalNumber decimalNumberBySubtracting:twoDecimalNumber withBehavior:decimalNumberHandler];
//乘
NSDecimalNumber *multiplyingRes = [oneDecimalNumber decimalNumberByMultiplyingBy:twoDecimalNumber withBehavior:decimalNumberHandler];
//除
NSDecimalNumber *divideRes = [oneDecimalNumber decimalNumberByDividingBy:twoDecimalNumber withBehavior:decimalNumberHandler];
//n次方
NSDecimalNumber *powerResult = [twoDecimalNumber decimalNumberByRaisingToPower:2
withBehavior:decimalNumberHandler];
NSLog(@"%@\n %@\n %@\n %@\n %@\n",addRes,subtractRes,multiplyingRes,divideRes,powerResult);
//¥198.99 85折后
NSDecimalNumber *total = [NSDecimalNumber decimalNumberWithString:@"198.99"];
NSDecimalNumber *discount = [NSDecimalNumber decimalNumberWithString:@".85"];
NSDecimalNumber *pay = [total decimalNumberByMultiplyingBy:discount withBehavior:decimalNumberHandler];
NSLog(@"¥198.99 85折后应付: ¥%@", pay);
//比较大小
NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:@".3"];
NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:@".9"];
NSComparisonResult result = [num1 compare:num2];
NSLog(@"num1 %@ num2", result > 0 ? @">":@"<");