有时候我们需要精确计算小数,比如精确计算金额,或者需要高精度计算一些数值等,使用系统默认的Float,Double,CGFloat等类型计算是不准确的。
我们需要使用系统提供的类NSDecimalNumber进行计算。
// 精确小数点计算
NSString *num1 = @"1.99999999999";
NSString *num2 = @"0.00000000001";
NSString *num3 = @"0.00000001234";
NSString *num4 = @"1.23456789876";
// 创建NSDecimalNumber对象
NSDecimalNumber *number1 = [NSDecimalNumber decimalNumberWithString:num1];
NSDecimalNumber *number2 = [NSDecimalNumber decimalNumberWithString:num2];
NSDecimalNumber *number3 = [NSDecimalNumber decimalNumberWithString:num3];
NSDecimalNumber *number4 = [NSDecimalNumber decimalNumberWithString:num4];
// 减
NSDecimalNumber *subNum = [number1 decimalNumberBySubtracting:number2];
NSLog(@"%@ - %@ = %@", number1.stringValue, number2.stringValue, subNum.stringValue);
// 加
NSDecimalNumber *sumNum = [number2 decimalNumberByAdding:number3];
NSLog(@"%@ + %@ = %@", number2.stringValue, number3.stringValue, sumNum.stringValue);
// 乘
NSDecimalNumber *multiNum = [number4 decimalNumberByMultiplyingBy:number2];
NSLog(@"%@ * %@ = %@", number4.stringValue, number2.stringValue, multiNum.stringValue);
// 除
NSDecimalNumber *dividNum = [number4 decimalNumberByDividingBy:number2];
NSLog(@"%@ / %@ = %@", number4.stringValue, number2.stringValue, dividNum.stringValue);
得到的结果
2015-12-10 23:30:10.106 test[3245:79623]
1.99999999999 - 0.00000000001 = 1.99999999998
2015-12-10 23:30:10.107 test[3245:79623]
0.00000000001 + 0.00000001234 = 0.00000001235
2015-12-10 23:30:10.107 test[3245:79623]
1.23456789876 * 0.00000000001 = 0.0000000000123456789876
2015-12-10 23:30:22.250 test[3245:79623]
1.23456789876 / 0.00000000001 = 123456789876