NSDecimalNumber的用法

04/01/2016 13:23 下午 posted in  apple

加减乘除 解决字符串转float类型不准确 结尾无法去0处理 用于货币处理

    //货币算法 使用NSDecimalNumber 来进行精准计算
    //float  double  在计算时会产生误差
     
    //加法
     
    //声明两个  NSDecimalNumber
    NSDecimalNumber *jiafa1 = [NSDecimalNumber decimalNumberWithString:@"55.55555"];
     
    NSDecimalNumber *jiafa2 = [NSDecimalNumber decimalNumberWithString:@"0.11111"];
     
     
    //加法运算函数  decimalNumberByAdding
    NSDecimalNumber *jiafa = [jiafa1 decimalNumberByAdding:jiafa2];
     
    NSLog(@"加法 %@", jiafa);
     
     
    //减法
     
    //声明两个  NSDecimalNumber
    NSDecimalNumber *jianfa1 = [NSDecimalNumber decimalNumberWithString:@"55.55555"];
     
    NSDecimalNumber *jianfa2 = [NSDecimalNumber decimalNumberWithString:@"0.11111"];
     
     
    //减法运算函数  decimalNumberByAdding
    NSDecimalNumber *jianfa = [jianfa1 decimalNumberBySubtracting:jianfa2];
     
    NSLog(@"减法 %@", jianfa);
     
     
    //乘法
     
    //声明两个  NSDecimalNumber
    NSDecimalNumber *chengfa1 = [NSDecimalNumber decimalNumberWithString:@"55.55555"];
     
    NSDecimalNumber *chengfa2 = [NSDecimalNumber decimalNumberWithString:@"0.11111"];
     
     
    //乘法运算函数  decimalNumberByAdding
    NSDecimalNumber *chengfa = [chengfa1 decimalNumberByMultiplyingBy:chengfa2];
     
    NSLog(@"乘法 %@", chengfa);
     
     
    //除法
     
    //声明两个  NSDecimalNumber
    NSDecimalNumber *chufa1 = [NSDecimalNumber decimalNumberWithString:@"55"];
     
    NSDecimalNumber *chufa2 = [NSDecimalNumber decimalNumberWithString:@"3"];
     
     
    //除法运算函数  decimalNumberByAdding
    NSDecimalNumber *chufa = [chufa1 decimalNumberByDividingBy:chufa2];