NSNumber Calculations and Accuracy?

Two quick questions, if I can, is how should I do two NSNumber objects, doing the calculations and ending with the result, which is also NSNumber?

NSNumber *flux = [[NSNumber alloc] initWithDouble:100.0];
NSNumber *mass = [[NSNumber alloc] initWithDouble:3];

double intermediate = [flux doubleValue] / [mass doubleValue];
NSLog(@"INTER : %.20f", intermediate);

NSNumber *result = [[NSNumber alloc] initWithDouble:intermediate];
NSLog(@"RESULT: %@", result);

...
...

[flux release];
[mass release];
[result release];

Also, looking at the results in the console from NSLog, is there any loss of accuracy? I would suggest that no, and what I see is just the accuracy of the display, but just curious?

INTER : 33.33333333333333570181
RESULT: 33.33333333333334

Gary

+3
source share
4 answers

(Tangential question, but related)

NSNumber is not intended to calculate base-10 math. This is largely for wrapping and storing numerical values. If you need to do real math, you want to use NSDecimal.

NSDecimalNumber, NSNumber, - base-10. , x 10 ^ - 38 , -128 127

, "", , . , . , , .

, - , NSDecimal NSNumber. NSDecimal .

Edit01:

... NSNumber, NSNumber?

, NSNumber . , NSNumber . , . , .

NSDecimal , . .

NSLog, - ?

, . Scala , . . , , NSInteger NSUInteger, NSInteger.

.

NSNumber , , , , , float , , FLT_MAX, , NSInteger.

NSDecimal . , , - .

: , NSNumber .

+14

NSNumber :

  • double: %0.16g
  • float: %0.7g

, , , , .

, double 16 . - ( -10).

+4

%@ , NSLog description . , NSNumber , - , NSLog. :

NSLog ("%.20f", [result doubleValue]);

, NSLog intermediate.

+2

NSNumbers NSValues ​​- . , , , .

0

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


All Articles