/**由于NSDecimalNumber能够存储很大的值(大到38位 x 10^+/-128)。这样进行一些大数值运算时也很方便,但是直接使用C的标量值会比通过NSDecimalNumber更快,所以需要慎重选择该方法。通常来说,这只在集合中使用。
*/
//NSDecimalNumber常见用法
//1.小数位处理及约数方式
NSDecimalNumberHandler * roundUp = [NSDecimalNumberHandlerdecimalNumberHandlerWithRoundingMode:NSRoundBankersscale:2raiseOnExactness:NOraiseOnOverflow:NOraiseOnUnderflow:NOraiseOnDivideByZero:YES]; //保留两位小数(scale)
/** RoundingMode:NSRoundPlain //貌似取整
NSRoundDown, // Always down == truncate //只舍不入
NSRoundUp, // Always up // 只入不舍
NSRoundBankers // on a tie round so last digit is even //貌似四舍五入
**/
NSDecimalNumber *subtotal = [NSDecimalNumberdecimalNumberWithString:@"90.7049"];
NSDecimalNumber *discount = [NSDecimalNumberdecimalNumberWithString:@"0.22"];
NSDecimalNumber *total = [subtotaldecimalNumberByAdding:discount withBehavior:roundUp];
//按照roundUp规定好的进行相加:四舍五入、保留两位小数
NSLog(@"Rounded total: %@", total);
//2.次方计算
NSDecimalNumber*price;
price = [NSDecimalNumberdecimalNumberWithMantissa:1599exponent:-2 //10的-2次方
isNegative:NO];
//等效于
price = [NSDecimalNumberdecimalNumberWithString:@"15.99"];
//3.加减乘除四则运算
NSDecimalNumber*price1 = [NSDecimalNumberdecimalNumberWithString:@"15.99"];
NSDecimalNumber*price2 = [NSDecimalNumberdecimalNumberWithString:@"29.99"];
NSDecimalNumber*coupon = [NSDecimalNumberdecimalNumberWithString:@"5.00"];
NSDecimalNumber*disCount = [NSDecimalNumberdecimalNumberWithString:@".90"];
NSDecimalNumber*numProducts = [NSDecimalNumberdecimalNumberWithString:@"2.0"];
NSDecimalNumber *subTotal = [price1decimalNumberByAdding:price2];//相加
NSDecimalNumber *afterCoupon = [subtotaldecimalNumberBySubtracting:coupon];//相减
NSDecimalNumber *afterDiscount = [afterCoupondecimalNumberByMultiplyingBy:disCount];//相乘
//按照roundUp规定好的进行相乘:四舍五入、保留两位小数
NSDecimalNumber*total2 = [subtotaldecimalNumberByMultiplyingBy:discountwithBehavior:roundUp];
NSDecimalNumber *average = [afterDiscountdecimalNumberByDividingBy:numProducts];//相除
NSDecimalNumber*averageSquared = [averagedecimalNumberByRaisingToPower:2];//平方
//4.比较大小
NSDecimalNumber*discount1 = [NSDecimalNumberdecimalNumberWithString:@".85"];
NSDecimalNumber*discount2 = [NSDecimalNumberdecimalNumberWithString:@".9"];
NSComparisonResult result = [discount1compare:discount2];
if (result ==NSOrderedAscending) {
NSLog(@"85%% < 90%%小于");
} elseif (result == NSOrderedSame) {
NSLog(@"85%% == 90%%等于");
} elseif (result == NSOrderedDescending) {
NSLog(@"85%% > 90%%大于");
}
网友评论