How to divide NSDecimalNumber by integer?
cocoa, ios
Solution
Is there any reason why you're using `NSDecimalNumber`? This can be done way easier like this:
// Inputs
NSString *amount_text = @"15.3";
int n = 10;
float amount = [amount_text floatValue];
float result = amount / n;
If you really want to do it with `NSDecimalNumber`:
// Inputs
NSString *amount_text = @"15.3";
int n = 10;
NSDecimalNumber *total = [NSDecimalNumber decimalNumberWithString:amount_text];
NSDecimalNumber *divisor = [NSDecimalNumber decimalNumberWithMantissa:n exponent:0 isNegative:NO];
NSDecimalNumber *contribution = [total decimalNumberByDividingBy:divisor];
Problem
I don't think a comprehensive, basic answer to this exists here yet, and googling didn't help. Task: Given an `NSDecimalNumber` divide this by an `int` and return another `NSDecimalNumber`. Clarification: `amount_text` below must be converted to a NSDecimalNumber because it is a currency. The result must be a NSDecimalNumber, but I don't care what format the divisor is. What I have so far: ``` // Inputs NSString *amount_text = @"15.3"; int n = 10; NSDecimalNumber *total = [NSDecimalNumber decimalNumberWithString:amount_text]; // Take int, convert to string. Take string, convert to NSDecimalNumber. NSString *int_string = [NSString stringWithFormat:@"%d", n]; NSDecimalNumber *divisor = [NSDecimalNumber decimalNumberWithString:int_string]; NSDecimalNumber *contribution = [total decimalNumberByDividingBy:divisor]; ``` Surely, this can be done in a more straightforward way?