Question

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!

Était-ce utile?

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

Autres conseils

Wrap the double into a BigDecimal first:

BigDecimal result = yourBigDecimal.multiply(new BigDecimal(yourDouble));

BigDecimal is not a primitive type. So you really cannot apply simple maths (*,-,+) into that. It has many methods in order to support all the basic mathematics. You can use them. As comment suggest read the java doc (http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html).

What big decimal has is a two main parts. One part contains the number, and the second part precision. So if you want to handle special maths which is not standard available you can get those two values separately and try with higher mathematical algorithms

Quate from java doc :

21/110 = 0.190 // integer=190, scale=3

Do sthg like this;

 public class Payment
 {
     BigDecimal itemCost;
     BigDecimal totalCost; // You can initialize it if you wish.

     public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
     {
         itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
         totalCost = totalCost.add(itemCost);
         return totalCost;
     }
 }

And read javadoc for BigDecimal.

Warning: Unpredictability of the BigDecimal(double) constructor

new Bigdecimal(myDouble) is wrong. You have to use Bigdecimal.valueOf(myDouble) instead.

BigDecimal multi = BigDecimal.valueOf(doubleValue).multiply(bigDecimal)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top