Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiply Bigdecimal and int generating error [duplicate]

I have one value like 0.0004 when I store this in Integer it is converting into Exponential format, So I have used Bigdecimal to convert it to normal value like below

 Bigdecimal x=BigDecimal.valueOf(0.0004)

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

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.

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

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

Thanks for your time

like image 213
Siva Avatar asked May 28 '26 21:05

Siva


1 Answers

You can use BigDecimal.multiply to multiply your BigDecimal.

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

Finally, you can alter the how the BigDecimal is represented in terms of fractional digits by using a NumberFormat instance and formatting your 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
like image 147
Mena Avatar answered May 31 '26 11:05

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!