views:

201

answers:

3

I wonder what's the point of NSDecimalNumber. It offers some arithmetics methods, but why should I use NSDecimalNumber and not just double or NSNumber? Did apple take care of some floating point arithmetics uglyness there? Would it make life easier when making heavy use of high precision and big floating point maths?

+2  A: 

NSDecimalNumber is a fixed precision (and scale) integer scaled to a certain size to represent fractional numbers. This is a little different from a floating point number (where the point, obviously, floats...)

As an example, say you need to represent money from 0.00 to 999.99, you could store this in an integer from 0 to 99999 as an amount in pennies. The scale (in digits) is 2 and the precision is 5. In a floating point number, with precision 5, and a floating point you could represent from .00001 to 99999, but not 999.999, for example.

Cade Roux
+2  A: 

This all depends or your needs. It is a trade off between precision, speed and size of data.

If you are writing an accounting application you cannot lose any precision and so might well use NSDecimal number.

Ig you are doing complex numerical analysis the speed could matter and so NSDecimalNumber would be too slow. But even in that case your analysis would look at the precision and errors you could afford and here could be cases where you need more precision that doubles etc give you.

NSNumber is a separate case it is a class cluster to allow storage of C type numbers in other objects and other use in Cocoa.

Mark
+2  A: 

If your software deals with money, or other non-integer numbers of interest to accountants, you are well advised to use decimal numbers for that (rather than the binary ones that the underlying HW is optimized to process); that's why all sorts of general purpose languages and databases bend over backwards to support decimal non-integer numbers, not just binary ones.

Rounding issues with binary non-integers might easily result in fractions-of-a-cent discrepancies that, at the limit, might even land you in legal trouble, and, more realistically, will be perceived by accountants and others dealing with money &c as errors in your program, no matter how staunchly you may argue otherwise!-)

Alex Martelli
a "binary non-integer" would be a double, for example?
HelloMoon
IRTFM: Floats and Doubles (doubles are just wider floats) are both binary non-integer types. Sometimes integers are used like binary non-integers if only a fixed amount of precision is needed (example: using a 64-bit integer to represent tenths of a cent)
rpetrich
Yep, float or fixed point numbers of any width. Even a simple 0.1 cannot be exactly represented in binary float or fixed point of any finite width. "work with integer numbers of cents" and the like still leaves you in a pickle wrt compound interest, mortgage schedules, etc.
Alex Martelli