开发者

iphone NSComparisonResult for two NSDecimalNumber objects fails

开发者 https://www.devze.com 2023-03-27 02:15 出处:网络
NSDecimalNumber *no1= [NSDecimalNumber decimalNumberWithString:[totalPotFund stringByReplacingOccurrencesOfString:@\",\" withString:@\".\"]];//consider totalPotFund = 301
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(@"A开发者_开发百科mount 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
}

Hi all, the problem I'm facing is that though -699 is lesser than 12, it still goes in the "if(res == NSOrderedAscending)" condition and not the "else" condition. Funny it should be doing that. I haven't got any example code as such for 2 NSDecimal numbers comparison with NSComparisonResult and send the compared result to NSOrderedAscending or NSOrderedDescending or NSOrderedSame.

Thanks in anticipation.


From the apple docs:

NSOrderedAscending if the value of decimalNumber is greater than the receiver; NSOrderedSame if they’re equal; and NSOrderedDescending if the value of decimalNumber is less than the receiver.

NSOrderedAscending is the correct result, since the argument (no3 = 12) is greater than the receiver (result = -699).


Read carefully the documentation: NSOrderedAscending is returned if decimalNumber > receiver. In your case receiver=result=-699 and decimalNumber=no3=12 so as decimalNumber>receiver then NSOrderedAscending is returned, as expected.

From Apple docs:

compare: Returns an NSComparisonResult value that indicates the numerical ordering of the receiver and another given NSDecimalNumber object.

  • (NSComparisonResult)compare:(NSNumber *)decimalNumber Parameters decimalNumber The number with which to compare the receiver.

Return Value NSOrderedAscending if the value of decimalNumber is greater than the receiver; NSOrderedSame if they’re equal; and NSOrderedDescending if the value of decimalNumber is less than the receiver.

0

精彩评论

暂无评论...
验证码 换一张
取 消