[Swift]NSDecimalNumberを使って四則演算を行うサンプル

サンプルコード

NSDecimalNumber *pcA = [NSDecimalNumber decimalNumberWithString:@"15.99"];
NSDecimalNumber *pcB = [NSDecimalNumber decimalNumberWithString:@"29.99"];
NSDecimalNumber *coupon = [NSDecimalNumber decimalNumberWithString:@"5.00"];
NSDecimalNumber *discount = [NSDecimalNumber decimalNumberWithString:@".90"];
NSDecimalNumber *numPs = [NSDecimalNumber decimalNumberWithString:@"2.0"];
    
// 足し算
NSDecimalNumber *subtotal = [pcA decimalNumberByAdding:pcB];
// 引き算
NSDecimalNumber *afterCoupon = [subtotal decimalNumberBySubtracting:coupon];
// 掛け算
NSDecimalNumber *afterDiscount = [afterCoupon decimalNumberByMultiplyingBy:discount];
 // 割り算
NSDecimalNumber *average = [afterDiscount decimalNumberByDividingBy:numPs];
// 累乗
NSDecimalNumber *averageSquared = [average decimalNumberByRaisingToPower:2];
    
NSLog(@"Subtotal: %@", subtotal);                    
NSLog(@"After coupon: %@", afterCoupon);          
NSLog((@"After discount: %@"), afterDiscount);       
NSLog(@"Average pc per product: %@", average);    
NSLog(@"Average pc squared: %@", averageSquared);

実行結果
45.98
40.98
36.882
18.441
340.070481

Swift

Posted by arkgame