Swift中金融变量的正确数字类型是什么? [英] What's the correct number type for financial variables in Swift?

查看:158
本文介绍了Swift中金融变量的正确数字类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于使用Java编程,其中 BigDecimal 类型最适合存储财务值,因为可以通过多种方式在计算中指定舍入规则.

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.

在最新的快速版本(撰写本文时为2.1)中,哪种本机类型更好地支持正确的计算和财务值的取整?有什么等效于Java的BigDecimal吗?还是类似的东西?

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?

推荐答案

如果您担心将例如$ 1.23存储在floatdouble中,以及从浮点精度错误中获得的潜在错误,那是如果您实际上想坚持整数美分或便士(或其他任何金额).然后使用整数存储您的值,并使用便士/分作为单位,而不是英镑/美元.这样一来,以整数便士/分进行交易时,您将100%准确,并且比使用NSDecimalNumber这样的类容易.那么,该值的显示纯粹是一个演示问题.

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.

但是,如果您需要处理一便士/分的几分之一,那么NSDecimalNumber可能就是您想要的.

If however you need to deal with fractions of a pence/cent, then NSDecimalNumber is probably what you want.

我建议研究类似的类如何实际工作,以及浮点数也如何工作,因为了解这一点将帮助您了解为什么会出现精度错误,以及像,为什么它更适合存储小数,为什么浮点数擅长存储17/262144之类的数字(即分母为2的幂),却不能存储1/100,等等.

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.

这篇关于Swift中金融变量的正确数字类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆