I have the following code:
double d1=1000000000000000000.0; //which is equivalent to 1.0e^18
double d2=3434.0;
System.out.println(d1+d2);
which prints 1000000000000003460 instead of 1000000000000003434. What is the problem?
I have the following code:
double d1=1000000000000000000.0; //which is equivalent to 1.0e^18
double d2=3434.0;
System.out.println(d1+d2);
which prints 1000000000000003460 instead of 1000000000000003434. What is the problem?
The problem is the double type itself, it doesn't support the precision you want. You should use BigDecimal.
The number of storage required exceeds the expected. Use BIG Decimal in cases like these.
import java.math.BigDecimal;//remember to import this
public class UseBigDecimal{
public static void main(String[]args){
double d1=1000000000000000000.0;
double d2=3434.0;
BigDecimal bVal1 = new BigDecimal(d1);
BigDecimal bVal2 = new BigDecimal(d2);
BigDecimal sum = bVal1.add(bVal2);//you call the add() method not bVal1+bVal2
System.out.println ("Sum of BigDecimals " +sum.toString());
//need to call toString()
}
}