Arithmetic NSNumber

I want to do some simple arithmetic in NSNumbers and save the type. Is it possible?

For instance:

- (NSNumber *)add:(NSNumber *)firstNumber to:(NSNumber *)secondNumber; 

Is the definition of my method, and firstNumber and secondNumber are integers, then I would like to return an integer, which is their integer. Similarly, if both are doubles, then to return the result as a double.

It looks like I can get the type (other than the boolean) using [NSNumber objCType] found in this question: get the type NSNumber , but I can't seem to extract these types and do the calculations without a lot of code to extract the values, do the calculation and return the result for each possible type.

Is there a short and concise way to do this?

+6
source share
3 answers

If you want to do arithmetic, the best option would be to use NSDecimalNumber .

NSDecimalNumber have methods for performing arithmetic operations, such as:

 – decimalNumberByAdding: – decimalNumberBySubtracting: – decimalNumberByMultiplyingBy: – decimalNumberByDividingBy: – decimalNumberByRaisingToPower: – decimalNumberByMultiplyingByPowerOf10: – decimalNumberByAdding:withBehavior: – decimalNumberBySubtracting:withBehavior: – decimalNumberByMultiplyingBy:withBehavior: – decimalNumberByDividingBy:withBehavior: – decimalNumberByRaisingToPower:withBehavior: – decimalNumberByMultiplyingByPowerOf10:withBehavior: 

And since NSDecimalNumber extends NSNumber, it also has all the NSNumber methods, so I think you can use it in your case without any problems.

+10
source

For almost all applications, it will be convenient to convert to double and back using -doubleValue and –initWithDouble: This will allow you to use the standard characters C (+, -, ...) and the functions ( exp() , sin() ). The only way you would run into a problem is to use maximum precision for 64-bit integer values.

If you want to stick with the operations of the Objective-C class, you can use NSDecimalNumber .

See also: How to add two NSNumber objects?

+3
source

How about calculating the value of an expression as double (with all inputs as double values) and then checking if the result is integer? Then you can use NSNumber numberWithInt: or NSNumber numberWithDouble: to return the result.

When you check if the result value is integer, be sure to consider the rounding error (for example, when 1 is expressed as 0.99999999, etc.).

EDIT . Just noticed in docs for NSNumber this phrase:

Note that numeric objects do not necessarily preserve the type that they are created with.

I think this means that you cannot reliably do what you are trying to do.

+2
source

Source: https://habr.com/ru/post/919965/


All Articles