有些时候在计算之后的结果会有要求保留一定位数精确值的情况:
比如:
//保留两位并四舍五入
NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
// 文本框
NSDecimalNumber *textNum = [NSDecimalNumber decimalNumberWithString:textStr];
// 现金券值
NSDecimalNumber *endShowMaxMoneyNum = [NSDecimalNumber decimalNumberWithString:self.endShowMaxCash];
// 计算计算保留两位并四舍五入
NSDecimalNumber *realReduceMoneyNum = [textNum decimalNumberBySubtracting:endShowMaxMoneyNum withBehavior:roundUp];
1、枚举值分析:
// Rounding policies :
// Original
// value 1.2 1.21 1.25 1.35 1.27
// Plain 1.2 1.2 1.3 1.4 1.3 四舍五入
// Down 1.2 1.2 1.2 1.3 1.2 向下取整
// Up 1.2 1.3 1.3 1.4 1.3 向上取整
// Bankers 1.2 1.2 1.2 1.4 1.3 (特殊的四舍五入,碰到保留位数后一位的数字为5时,根据前一位的奇偶性决定。为偶时向下取整,为奇数时向上取整。如:1.25保留1为小数。5之前是2偶数向下取整1.2;1.35保留1位小数时。5之前为3奇数,向上取整1.4)
typedef NS_ENUM(NSUInteger, NSRoundingMode) {
NSRoundPlain, // Round up on a tie
NSRoundDown, // Always down == truncate
NSRoundUp, // Always up
NSRoundBankers // on a tie round so last digit is even
};
2、参数分析:
//scale:保留有效小数的个数(为0的无效小数后自动过滤).
//Exactness:进度异常、
//Overflow:向上溢出、
//Underflow:向下溢出、
//DivideByZero:除数为0。当参数为YES出错会抛出异常,为NO时忽略异常。返回nil.
NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler
decimalNumberHandlerWithRoundingMode:NSRoundUp
scale:2
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:YES];