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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:37:03  来源:igfitidea点击:

BigDecimal math operations

javaobjectbigdecimal

提问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

BigDecimalhas no divide(int)method, but that's what you're asking it to do with .divide(100), because 100is an intliteral. If you refer to the documentation, all of the dividemethods accept BigDecimalinstances.

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 intcan be promoted to long.)

(它接受long[或double],但int可以提升为long。)

Alternately, for some values, you might use the Stringconstructor 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. 100is fine for valueOf, though.

...特别是如果您正在处理可能在double. 不过,100对 来说很好valueOf

回答by Pavlo Plynko

c = a.subtract(a.multiply(b).divide(BigDecimal.valueOf(100.0)));