Reputation: 1373
How can I do accurate decimal number arithmetic since using floats is not reliable? I still want to return the answer to a textField.
Upvotes: 1
Views: 482
Reputation: 523774
You can either use int
-s (e.g. with "cents" as a unit instead of "dollars"), or use NSDecimalNumber
s.
Upvotes: 2
Reputation: 95420
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.
Upvotes: 0