ios 涉及到支付金额计算的相关总结
1.支付服务端统一传的类型是 NSString
2.本地存的类型是 double
3.涉及到 乘法和除法使用
//两个double相乘 - (double)numberMeetWith:(double)num1 andNum:(double)num2 { NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundBankers scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES]; NSDecimalNumber *dec1 = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",num1]]; NSDecimalNumber *dec2 = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",num2]]; NSDecimalNumber *multiplyResult = [dec1 decimalNumberByMultiplyingBy:dec2 withBehavior:handler]; return [multiplyResult doubleValue]; } //两个double相除 - (double)numberDivisionWith:(double)num1 andNum:(double)num2 { NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundBankers scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES]; NSDecimalNumber *dec1 = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",num1]]; NSDecimalNumber *dec2 = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:@"%f",num2]]; NSDecimalNumber *multiplyResult = [dec1 decimalNumberByDividingBy:dec2 withBehavior:handler]; return [multiplyResult doubleValue]; }
4.double去零
- (NSString *)stringDisposeWithFloat:(double)floatValue { NSString *str = [NSString stringWithFormat:@"%f",floatValue]; long len = str.length; for (int i = 0; i < len; i++) { if (![str hasSuffix:@"0"]) break; else str = [str substringToIndex:[str length]-1]; } if ([str hasSuffix:@"."])//避免像2.0000这样的被解析成2. { //s.substring(0, len - i - 1); return [str substringToIndex:[str length]-1]; } else { return str; } }
5.使用示例
AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; double iphoneDayPrice = [self numberMeetWith:app.QZBIphoneOutTimeDayPrice andNum:[ordModel.outTimeDay doubleValue]]; double needAllMoney = iphoneDayPrice + [ordModel.repurchaseAmount doubleValue] - [self.orderDetailModel.repurchaseOffsetAmount doubleValue]; //转成NSString [self stringDisposeWithFloat:app.QZBIphoneOutTimeDayPrice]