最近在做一个分期支付的功能, 跟钱有关, 所以需要计算的特别精确, 不能有一分一厘的差距, 而且计算的中间还有一个需要向下取整 , 刚开始各种用float , double, int 等等 计算都不行, 总是出现小数点后计算不精确的问题. 最后仿照java里 bigDecimal计算, 猜想oc应该也有decimal计算方法, 上网一搜, 还真有.
经过N多次试验发现, %.2f 并不是直接截取小数点后2位, 而是四舍五入后的保留两位
以下是代码, 精确计算, 包括小数点后保留几位, 及保留的时候是四舍五入保留还是向上或向下取整保留:
NSDecimalNumberHandler 这个是控制如何取整及小数点后保留几位, NSRoundDown / NSRoundUp/NSRoundPlain 向下/向上/四舍五入取整
NSDecimalNumberHandler *roundDown = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
// 首付款, 不含最后一期的分期本金
NSDecimalNumber *pp = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f", ppMoney]];
NSDecimalNumber *downPay = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f", rateDownPayment]];
NSDecimalNumber *shoufukuan = [pp decimalNumberByMultiplyingBy:downPay];
// 总的分期本金
NSDecimalNumber *zongFenQiBenJin = [pp decimalNumberBySubtracting:shoufukuan];
// 每期的分期本金 = 总的分期本金 / 期数 (小数点后两位向下取整)
NSDecimalNumber *qishu = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f", installmentNum]];
NSDecimalNumber *meiQiFenQiBenJin = [[zongFenQiBenJin decimalNumberByDividingBy:qishu] decimalNumberByRoundingAccordingToBehavior:roundDown];
double meiqifenqibenjin = meiQiFenQiBenJin.doubleValue;
// 总的利息 = 总的分期本金 * 费率
// 每期的利息 = 总的利息 / 期数 (小数点后两位向下取整)
NSDecimalNumber *rate = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f", rateLoan]];
NSDecimalNumber *cheng = [zongFenQiBenJin decimalNumberByMultiplyingBy:rate];
NSDecimalNumber *num = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f", installmentNum]];
NSDecimalNumber *mq = [cheng decimalNumberByDividingBy:num];
NSDecimalNumber *meiQi = [mq decimalNumberByRoundingAccordingToBehavior:roundDown];
double meiqilixi = meiQi.doubleValue;