I'm working on an app that involves doing financial calculations. I see that Swift has both a Double and a Decimal type. Is it more appropriate to use the Decimal type for these calculations? As I'm working through some examples, I see that Decimal is more limited in terms of operations like rounding numbers, etc.
I would recommend Decimal
and I use it myself for financial applications.
You can recover rounding functionality using NSDecimalRound
which is available cross platform. That can be used to make some more swifty rounding extensions.
Be careful with Decimal
in the form it is currently shipping: there have been some known bugs, some of which I have tried to stamp out in the open source version and which have not been integrated back into Apple’s proprietary overlay, and other problems may lurk. A number of rounding APIs offered are simply not implemented.
If you are doing actual financial processing with real money, create and test your own Swift wrapper for a tried-and-true third-party decimal implementation, or use some alternative approach. Test, test, test. Without knowing your own use case it’s hard to make any specific recommendations, and in any case, if you’re working with real money, I wouldn’t base any decisions on any one person’s recommendations on an Internet forum anyway.
I know it's an old thread, but it's worth emphasising:
YOU SHOULD NEVER* USE FLOATING POINT FOR FINANCIAL CALCULATIONS
Decimal
is potentially a good choice, or you can just use integers and hold everything in cents or thousandths of a cent, or whatever makes sense for your application.