问题描述
我知道double / float的问题,建议使用BigDecimal而不是double / float表示货币字段。但双/浮动更有效和节省空间。然后我的问题是:
可以使用double / float来表示Java类中的货币字段,但是使用BigDecimal来处理算术(即在任何算术之前将double / float转换为BigDecimal)和等待检查?
I know the problem with double/float, and it's recommended to use BigDecimal instead of double/float to represent monetary fields. But double/float is more effective and space-saving. Then my question is:It's acceptable to use double/float to represent monetary fields in Java class, but use BigDecimal to take care of the arithmetic (i.e. convert double/float to BigDecimal before any arithmetic) and equal-checking?
原因是为了节省一些空间。而我真的看到很多项目正在使用double / float代表货币领域。
The reason is to save some space. And I really see lots of projects are using double/float to represent the monetary fields.
这是否有任何陷阱?
提前感谢
Is there any pitfall for this?Thanks in advance.
推荐答案
不,你不能。
假设 double
足以存储两个值 x
和 y
。然后将它们转换为安全的
BigDecimal
和多个它们。结果是准确的,但是如果您将乘法结果存储在 double
中,则可能会降低精度。证明:
Suppose
double
is enough to store two values x
and y
. Then you convert them to safe BigDecimal
and multiple them. The result is accurate, however if you store the multiplication result back in double
, chances are you will loose the precision. Proof:
double x = 1234567891234.0;
double y = 1234567891234.0;
System.out.println(x);
System.out.println(y);
BigDecimal bigZ = new BigDecimal(x).multiply(new BigDecimal(y));
double z = bigZ.doubleValue();
System.out.println(bigZ);
System.out.println(z);
结果:
1.234567891234E12 //precise 'x'
1.234567891234E12 //precise 'y'
1524157878065965654042756 //precise 'x * y'
1.5241578780659657E24 //loosing precision
x
和 y
是准确的,以及使用 BigDecimal
的乘法。但是,在转回 double
之后,我们会放宽最低有效位数。
x
and y
are accurate, as well as the multiplication using BigDecimal
. However after casting back to double
we loose least significant digits.
这篇关于我们可以使用double来存储货币领域,并使用BigDecimal进行算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!