I am used to programming in Java, where the BigDecimal type is the best for storing financial values, since there are manners to specify rounding rules over the calculations.
In the latest swift version (2.1 at the time this post is written), which native type better supports correct calculations and rounding for financial values? Is there any equivalent to java's BigDecimal? Or anything similar?
You can use
NSDecimal
orNSDecimalNumber
for arbitrary precision numbers.See more on
NSDecimalNumbers
's reference page.If you are concerned about storing for example $1.23 in a
float
ordouble
, and the potential inaccuracies you will get from floating point precision errors, that is if you actually want to stick to integer amounts of cents or pence (or whatever else). Then use an integer to store your value and use the pence/cent as your unit instead of pounds/dollars. You will then be 100% accurate when dealing in integer amounts of pence/cents, and it's easier than using a class likeNSDecimalNumber
. The display of that value is then purely a presentation issue.If however you need to deal with fractions of a pence/cent, then
NSDecimalNumber
is probably what you want.I recommend looking into how classes like this actually work, and how floating point numbers work too, because having an understanding of this will help you to see why precision errors arise and just what the precision limits are of a class like
NSDecimalNumber
, why it's better for storing decimal numbers, why floats are good at storing numbers like 17/262144 (i.e. where the denominator is a power of two) but can't store 1/100, etc.