基础应用

NSDecimalNumber基本使用

2019-03-19  本文已影响0人  蚂蚁牙齿不黑

作用

NSDecimalNumber继承自NSNumber,用于对浮点型数据的精度计算

加减乘除以及乘方

    NSDecimalNumber *price1 = [NSDecimalNumber decimalNumberWithString:@"15.99"];
    NSDecimalNumber *price2 = [NSDecimalNumber decimalNumberWithString:@"29.99"];
    NSDecimalNumber *coupon = [NSDecimalNumber decimalNumberWithString:@"5.00"];
    NSDecimalNumber *discount = [NSDecimalNumber decimalNumberWithString:@".90"];
    NSDecimalNumber *numProducts = [NSDecimalNumber decimalNumberWithString:@"2.0"];
    
    // 加
    NSDecimalNumber *subtotal = [price1 decimalNumberByAdding:price2];
    // 减
    NSDecimalNumber *afterCoupon = [subtotal decimalNumberBySubtracting:coupon];
    // 乘
    NSDecimalNumber *afterDiscount = [afterCoupon decimalNumberByMultiplyingBy:discount];
    // 除
    NSDecimalNumber *average = [afterDiscount decimalNumberByDividingBy:numProducts];
    // 乘方
    NSDecimalNumber *averageSquared = [average decimalNumberByRaisingToPower:2];
    
    NSLog(@"Subtotal: %@", subtotal);                    // 45.98
    NSLog(@"After coupon: %@", afterCoupon);           // 40.98
    NSLog((@"After discount: %@"), afterDiscount);       // 36.882
    NSLog(@"Average price per product: %@", average);    // 18.441
    NSLog(@"Average price squared: %@", averageSquared); // 340.070481

数值处理

    /*
     NSRoundPlain:四舍五入  NSRoundDown:向下取正   NSRoundUp:向上取正     NSRoundBankers:(特殊的四舍五入,碰到保留位数后一位的数字为5时,根据前一位的奇偶性决定。为偶时向下取正,为奇数时向上取正。如:1.25保留1为小数。5之前是2偶数向下取正1.2;1.35保留1位小数时。5之前为3奇数,向上取正1.4)
     scale:精确到几位小数
     raiseOnExactness:发生精确错误时是否抛出异常,一般为NO
     raiseOnOverflow:发生溢出错误时是否抛出异常,一般为NO
     raiseOnUnderflow:发生不足错误时是否抛出异常,一般为NO
     raiseOnDivideByZero:被0除时是否抛出异常,一般为YES
     */
    NSDecimalNumber * inputNumber = [[NSDecimalNumber alloc]initWithString:@"340.0700001"];
    NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler
                                       decimalNumberHandlerWithRoundingMode:NSRoundDown
                                       scale:2
                                       raiseOnExactness:NO
                                       raiseOnOverflow:NO
                                       raiseOnUnderflow:NO
                                       raiseOnDivideByZero:YES];
    NSDecimalNumber * number = [inputNumber decimalNumberByRoundingAccordingToBehavior: roundUp];
    NSLog(@"%@",number);
上一篇下一篇

猜你喜欢

热点阅读