Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide NSDecimalNumber by integer?

Tags:

ios

cocoa

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?

like image 463
Unapiedra Avatar asked Dec 19 '22 20:12

Unapiedra


2 Answers

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];
like image 147
DrummerB Avatar answered Jan 13 '23 03:01

DrummerB


You can always use initialisers when creating NSDecimalNumber. Since it is a subclass of NSNumber, NSDecimalNumber overrides initialisers.

So you can do

NSDecimalNumber *decimalNumber = [[NSDecimalNumber alloc] initWithInt:10];

however, you should be careful if your are doing high precision calculations as there are some problems using these initialisers. You can read about it here in more detail.

like image 29
mrt Avatar answered Jan 13 '23 03:01

mrt