说我对这些ivars有以下值:
NSString *百分比= 35 NSString *值= 146
在我的下面的代码中,当我进行乘法运算时(146 * .35),我希望得到51.1,而不是100。
- (NSDecimalNumber*) getProductByPercentage : (NSArray*) itemsToMultiply : (float) annualPatients {
//get items from array
NSString* percentage = [itemsToMultiply objectAtIndex:0];
NSString* value = [itemsToMultiply objectAtIndex:1];
//init a number formatter
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
//set its formatting style
[f setNumberStyle:NSNumberFormatterDecimalStyle];
//convert to percentage
float thisPercentage = [percentage floatValue]/100;
//convert to NSDecimal
NSDecimalNumber* decPercentage = [[NSDecimalNumber alloc] initWithString:[NSString stringWithFormat:@"%f", thisPercentage]];
NSDecimalNumber* decAvgReimbursement = [[NSDecimalNumber alloc] initWithString: value];
NSDecimalNumber* decAnnualPatients = [[NSDecimalNumber alloc] initWithString:[NSString stringWithFormat:@"%f", annualPatients]];
//set up handler
NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
scale:-2
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:NO
];
//get our results
NSDecimalNumber* decAvgCost = [decAvgReimbursement decimalNumberByMultiplyingBy:decPercentage
withBehavior:handler];
NSLog(@"%@::%@::%@", decAvgCost, decAvgReimbursement, decPercentage);
return decAvgCost;
}
这是我的日志输出
2013-02-04 13:57:46.960 EUS Calculator[34154:c07] 100::146::0.35
我的处理程序是否有问题导致错误的结果?
答案 0 :(得分:2)
scale:-2
您将比例设置为舍入到-2的小数,即最接近的100。
答案 1 :(得分:1)
答案 2 :(得分:1)
改变这个:
float thisPercentage = [percentage floatValue]/100;
到此:
float thisPercentage = [percentage floatValue]/100.0;
如果你没有放入.0,那么编译器将它解释为整数,当执行float / int时,它会将它转换为int,将你期望的0.35转换为0。
此外,您没有在任何地方使用NSNumberFormatter,因此您甚至不能创建它。
为什么你还在使用NSDecimalNumbers
?