tags:

views:

73

answers:

2

How can I do accurate decimal number arithmetic since using floats is not reliable? I still want to return the answer to a textField.

+2  A: 

You can either use int-s (e.g. with "cents" as a unit instead of "dollars"), or use NSDecimalNumber s.

KennyTM
Beat me to it; I kept thinking "I *know* there's an equivalent of Java's BigDecimal, I just can't remember what it's called..." :-) Added a link to the docs.
T.J. Crowder
thanks. how do you convert the NSDecimalNumber to NSString?
A: 

Store your number multiplied by some power of ten of your choice, chosen by the amount of precision you need to the right of the decimal point. We'll call these scaled numbers. Convert entered values that need your precision into scaled numbers. Addition is easy: just add. Multiplication is slightly harder: just multiply two scaled numbers, and then divide by your scale factor. Division is easy: just divide, then multiply by the scale factor. The only inconvenience is you'll have to write your own numeric input/output conversion routines.

Ira Baxter