IOS开发银行系统的四舍五入的算法
-(void)makeUi
{
NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler
decimalNumberHandlerWithRoundingMode:NSRoundBankers
scale:2
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:YES];
// 枚举
// NSRoundPlain, // Round up on a tie //貌似取整 翻译出来是个圆 吗的垃圾百度翻译
//NSRoundDown, // Always down == truncate //只舍不入
//NSRoundUp, // Always up // 只入不舍
//NSRoundBankers // on a tie round so last digit is even 貌似四舍五入
//90.7049+0.22 然后四舍五入
//NSDecimalNumber *subtotal = [NSDecimalNumberdecimalNumberWithString:@"90.7049"];
//NSDecimalNumber *discount = [NSDecimalNumberdecimalNumberWithString:@"0.22"];
NSDecimalNumber *subtotal = [NSDecimalNumber decimalNumberWithString:@"90.706"];
NSDecimalNumber *discount = [NSDecimalNumber decimalNumberWithString:@"0.224"];
NSDecimalNumber *total = [subtotal decimalNumberByAdding:discount withBehavior:roundUp];
NSDecimalNumber *NSRoundBankers = [subtotal decimalNumberByRoundingAccordingToBehavior:roundUp];
//NSDecimalNumber *total = [subtotal decimalNumberByAdding:discount withBehavior:roundUp];
NSLog(@"Rounded total: %@--------%@", total,NSRoundBankers);
}
算法解释‘;
银行家舍入(Banker's Round)这个方法的,其规则如下:
舍去位的数值小于5时,直接舍去;舍去位的数值大于等于6时,进位后舍去;
当舍去位的数值等于5时,分两种情况:5后面还有其他数字(非0),则进位后舍去;若5后面是0(即5是最后一位),则根据5前一位数的奇偶性来判断是否需要进位,奇数进位,偶数舍去。