1. 程式人生 > >iOS 浮點數精確計算(資料處理)

iOS 浮點數精確計算(資料處理)

有時候我們需要精確計算小數,比如精確計算金額,或者需要高精度計算一些數值等,使用系統預設的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