Java 乘以 Bigdecimal 和 int 生成错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24289391/
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-08-14 11:19:32  来源:igfitidea点击:

multiply Bigdecimal and int generating error

javaandroidintbigdecimal

提问by Siva

I have one value like 0.0004when I store this in Integerit is converting into Exponentialformat, So I have used Bigdecimalto convert it to normal value like below

我有一个值,就像0.0004我将Integer它存储在其中时正在转换为Exponential格式一样,所以我曾经Bigdecimal将其转换为正常值,如下所示

 Bigdecimal x=BigDecimal.valueOf(0.0004)

Now I am trying to multiply as x*100but I am getting below error.

现在我正试图乘以x*100但我得到低于错误。

Error: The operator * is undefined for the argument type(s) BigDecimal, int

Because of this error if I use this without bigdecimal again it is converting to EXponential.

由于这个错误,如果我在没有 bigdecimal 的情况下再次使用它,它会转换为EXponential.

Can any one please suggest me the way to multiply Bigdecimal and int.

任何人都可以请给我建议乘法Bigdecimal and int

googled a lot but couldn't find the correct solution.

谷歌搜索了很多,但找不到正确的解决方案。

Thanks for your time

谢谢你的时间

采纳答案by Mena

You can use BigDecimal.multiplyto multiply your BigDecimal.

您可以使用BigDecimal.multiply乘以您的BigDecimal.

However, the int value of 0.0004 * 100will be 0, which is probably not what you want.

但是,0.0004 * 100will的 int 值0可能不是您想要的。

Finally, you can alter the how the BigDecimalis represented in terms of fractional digits by using a NumberFormatinstance and formatting your Number.

最后,您可以BigDecimal通过使用NumberFormat实例并格式化您的Number.

Here's an example:

下面是一个例子:

BigDecimal x= BigDecimal.valueOf(0.0004);
BigDecimal y = x.multiply(new BigDecimal("100"));
int z = y.intValue();
System.out.printf("y is %s\tz is %d%n", y, z);
// edit to truncate fractional digits
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
System.out.printf("y (2 fraction digits) is %s", nf.format(y));

Output

输出

y is 0.04000    z is 0
y (2 fraction digits) is 0.04

回答by Anubian Noob

BigDecimal's are objects. They don't have normal operators.

BigDecimal是对象。他们没有普通的操作员。

Instead of a normal multiplication operator like x*10, you need to call the method multiplyin BigDecimal:

x*10您需要multiply在 BigDecimal 中调用该方法,而不是像 那样的普通乘法运算符:

x = x.multiply(new BigDecimal(10));

If you want to store it in a new value:

如果要将其存储在新值中:

BigDecimal n = x.multiply(new BigDecimal(10));

And to convert that to a primative:

并将其转换为原始:

double d = n.doubleValue();
int i = n.intValue();

However, if you're trying to use decimals, why not just use a double:

但是,如果您尝试使用小数,为什么不使用双精度数:

double x = 0.0004;
double n = x*100;