What's the correct number type for financial v

2019-07-25 03:14发布

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?

2条回答
乱世女痞
2楼-- · 2019-07-25 03:48

You can use NSDecimal or NSDecimalNumber for arbitrary precision numbers.

See more on NSDecimalNumbers's reference page.

查看更多
男人必须洒脱
3楼-- · 2019-07-25 03:50

If you are concerned about storing for example $1.23 in a float or double, 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 like NSDecimalNumber. 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.

查看更多
登录 后发表回答