两个NSDecimalNumber对象的iphone NSComparisonResult失败

时间:2011-08-11 11:43:22

标签: iphone ios ios4

NSDecimalNumber *no1    = [NSDecimalNumber decimalNumberWithString:[totalPotFund stringByReplacingOccurrencesOfString:@"," withString:@"."]];//consider totalPotFund = 301
NSLog(@"Total Bank Fund: %@", totalPotFund);

NSDecimalNumber *no2    = [NSDecimalNumber decimalNumberWithString:[MinimumFund stringByReplacingOccurrencesOfString:@"," withString:@"."]];//consider MinimumFund = 1000
NSLog(@"Debet: %@", MinimumFund);

NSDecimalNumber *result = [no1 decimalNumberBySubtracting:no2];//301 - 1000 = -699
NSLog(@"Result = Total Bank Fund - Debet: %@ - %@ = %@", totalPotFund, MinimumFund, result);

NSDecimalNumber *no3  = [NSDecimalNumber decimalNumberWithString:[payAmt.text stringByReplacingOccurrencesOfString:@"," withString:@"."]];//consider payAmt = 12
NSLog(@"Amount to be paid: %@", payAmt.text);

NSComparisonResult res = [result compare:no3]; //-699 compare 12: -699 < 12

NSLog(@"Compare Resultant Amount with CheckOut Amount: %@ compare %@", result, no3);//

if(res == NSOrderedAscending)
{
    Do Something
}
else
{
    Do The Other Thing
}

大家好,我面临的问题是虽然-699小于12,但仍然存在 &#34; if(res == NSOrderedAscending)&#34;条件而不是&#34;否则&#34;条件。有趣的是它应该这样做。我没有得到任何示例代码,因为2 NSDecimal数字与NSComparisonResult比较,并将比较结果发送到NSOrderedAscending或NSOrderedDescending或NSOrderedSame。

感谢您的期待。

2 个答案:

答案 0 :(得分:3)

来自apple docs:

  

如果decimalNumber的值大于,则NSOrderedAscending   接收器; NSOrderedSame如果他们是平等的;和NSOrderedDescending if   decimalNumber的值小于接收者。

NSOrderedAscending是正确的结果,因为参数(no3 = 12)大于接收者(结果= -699)。

答案 1 :(得分:0)

仔细阅读文档:如果decimalNumber&gt;返回NSOrderedAscending。接收器。在你的情况下,receiver = result = -699和decimalNumber = no3 = 12以及decimalNumber&gt;接收器,然后按预期返回NSOrderedAscending。

来自Apple文档:

比较: 返回NSComparisonResult值,该值指示接收器和另一个给定NSDecimalNumber对象的数字排序。

  • (NSComparisonResult)比较:(NSNumber *)decimalNumber 参数 DecimalNumber设置 用于比较接收器的数量。

返回值 如果decimalNumber的值大于接收者,则NSOrderedAscending; NSOrderedSame如果他们是平等的;如果decimalNumber的值小于接收者,则为NSOrderedDescending。