关于OC中的精度计算NSDecimalNumber

//NSDecimalNumber是NSNumber的子类,是苹果针对浮点型计算时存在精度计算误差的问题而提供
的一个类

计算相关

NSString *str1 = @"100.90";
NSString *str2 = @"100.09";

NSDecimalNumber *decimal1 = [NSDecimalNumber decimalNumberWithString:str1];
NSDecimalNumber *decimal2 = [NSDecimalNumber decimalNumberWithString:str2];

//加
NSDecimalNumber *addDecimal = [decimal1 decimalNumberByAdding:decimal2];
NSLog(@"%@",addDecimal);

//减
NSDecimalNumber *subtractDecimal = [decimal1 decimalNumberBySubtracting:decimal2];
NSLog(@"%@",subtractDecimal);

//乘
NSDecimalNumber *multiplyDeciaml = [decimal1 decimalNumberByMultiplyingBy:decimal2];
NSLog(@"%@",multiplyDeciaml);

//除
NSDecimalNumber *dividDecimal = [decimal1 decimalNumberByDividingBy:decimal2];
NSLog(@"%@",dividDecimal);

//次方运算
NSDecimalNumber *raisingDecimal = [decimal1 decimalNumberByRaisingToPower:0];
NSLog(@"%@",raisingDecimal);

//10次方
NSDecimalNumber *multiplyingByPowerOf10Decimal = [decimal1 decimalNumberByRaisingToPower:10];
NSLog(@"%@",multiplyingByPowerOf10Decimal);

NSString和double转换

/*
 *double ---> NSString
 */
- (NSString *)decimalNumberWithDouble:(double)conversionValue {
    NSString *doubleString     = [NSString stringWithFormat:@"%lf",conversionValue];
    NSDecimalNumber *decNumber = [NSDecimalNumber decimalNumberWithString:doubleString];
    return [decNumber stringValue];
}
/*
 *NSString ---> double
 */
- (double)StringChangeToDoubleForJingdu:(NSString *)textString {
    if (textString == nil || [textString isEqualToString:@""]) {
        return 0.0;
    }
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    return  [[formatter numberFromString:textString]doubleValue];
}

你可能感兴趣的:(关于OC中的精度计算NSDecimalNumber)