Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operations with BigDecimal and double in Java

I am trying to use Advogadro's number (6.022*10^23) in a java program and i use BigDecimal variable to store it. However i want to multiply it with an int or a double and still keep the precision, but it throws an error!

bad operand types for binary operator '*'
  first type:  double
  second type: BigDecimal

Is there any simple way to do that? Also is there a way to print the result in scientific notation?

Thanks in advance!

like image 920
Angelo Uknown Avatar asked Jun 16 '26 14:06

Angelo Uknown


2 Answers

Operations are only supported for primitive types (and + for Strings)

BigDecimals has implemented the operations as functions.

you can only uses BigDecimals for operations with BigDecimals. So you need to convert your double value:

BigDecimal result = new BigDecimal(doubleValue).multiply(factor2);
like image 62
Philipp Sander Avatar answered Jun 19 '26 03:06

Philipp Sander


Wrap the double into a BigDecimal first:

BigDecimal result = yourBigDecimal.multiply(new BigDecimal(yourDouble));
like image 27
Martin Dinov Avatar answered Jun 19 '26 04:06

Martin Dinov



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!