NSDecimalNumberの簡単なまとめ

NSDecimalNumberの扱いを簡単にまとめました。
生成や変換は、文字列との相性が良いようです。

文字列から作成

NSDecimalNumber *dNum = [NSDecimalNumber decimalNumberWithString:@"1.234"];
NSDecimalNumber *dZero = [NSDecimalNumber zero];

文字列に変換

NSString *dNumStr = [dNum stringValue];

加減乗除

NSDecimalNumber *dNum1 = [NSDecimalNumber decimalNumberWithString:@"1.234"];
NSDecimalNumber *dNum2 = [NSDecimalNumber decimalNumberWithString:@"5.678"];

// dNum1 + dNum2
NSDecimalNumber *sum = [dNum1 decimalNumberByAdding:dNum2];
// dNum1 - dNum2
NSDecimalNumber *sub = [dNum1 decimalNumberBySubtracting:dNum2];
// dNum1 * dNum2
NSDecimalNumber *times = [dNum1 decimalNumberByMultiplyingBy:dNum2];
// dNum1 / dNum2
NSDecimalNumber *div = [dNum1 decimalNumberByDividingBy:dNum2];

四捨五入(小数点以下2桁の例)

NSDecimalNumberHandler *round = [NSDecimalNumberHandler
                                 decimalNumberHandlerWithRoundingMode:NSRoundPlain
                                 scale:2
                                 raiseOnExactness:NO
                                 raiseOnOverflow:NO
                                 raiseOnUnderflow:NO
                                 raiseOnDivideByZero:YES];
NSDecimalNumber *rounded = [dNum1 decimalNumberByMultiplyingBy:dNum2 withBehavior:round];

比較

NSComparisonResult result = [dNum1 compare:dNum2];
if (result == NSOrderedAscending) {
    NSLog(@"dNum1 < dNum2");
} else if (result == NSOrderedSame) {
    NSLog(@"dNum1 == dNum2");
} else if (result == NSOrderedDescending) {
    NSLog(@"dNum1 > dNum2");
}

コメント