java BigDecimal 数学运算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42413020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BigDecimal math operations
提问by blaa
I want to write this in Java but I get some errors and I am not sure how to write it:
我想用 Java 编写此代码,但出现一些错误,而且我不知道如何编写:
C = A - (A*B)/100
All of my values are defined as Bigdecimal objects.
我的所有值都定义为 Bigdecimal 对象。
I tried something like this but is not working:
我试过这样的事情,但没有奏效:
C = A.subtract(A.multiply(B).divide(100));
..I get a warning to add more arguments to the divide method. I do not know how to write it correctly. What am I doing wrong? Thanks in advance
..我收到一条警告,要求向divide 方法添加更多参数。我不知道如何正确地写。我究竟做错了什么?提前致谢
回答by T.J. Crowder
BigDecimal
has no divide(int)
method, but that's what you're asking it to do with .divide(100)
, because 100
is an int
literal. If you refer to the documentation, all of the divide
methods accept BigDecimal
instances.
BigDecimal
没有divide(int)
方法,但这就是你要求它做的事情.divide(100)
,因为它100
是一个int
文字。如果您参考文档,则所有divide
方法都接受BigDecimal
实例。
You can use divide(BigDecimal)
instead, by using BigDecimal.valueOf
:
您可以divide(BigDecimal)
改为使用BigDecimal.valueOf
:
C = A.subtract(A.multiply(B).divide(BigDecimal.valueOf(100)));
(It accepts a long
[or double
], but int
can be promoted to long
.)
(它接受long
[或double
],但int
可以提升为long
。)
Alternately, for some values, you might use the String
constructor instead:
或者,对于某些值,您可以改用String
构造函数:
C = A.subtract(A.multiply(B).divide(new BigDecimal("100")));
...particularly if you're dealing with floating-point values that might lose precision in double
. 100
is fine for valueOf
, though.
...特别是如果您正在处理可能在double
. 不过,100
对 来说很好valueOf
。
回答by Pavlo Plynko
c = a.subtract(a.multiply(b).divide(BigDecimal.valueOf(100.0)));