Search code examples
javavariablesdoublebigdecimal

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!


Solution

  • 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);