shin
shin

Reputation: 1681

Mistake while adding double values in java

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?

Upvotes: 1

Views: 2049

Answers (3)

karto
karto

Reputation: 3668

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()
   }

  }

Upvotes: 0

belgther
belgther

Reputation: 2534

The problem is the double type itself, it doesn't support the precision you want. You should use BigDecimal.

Upvotes: 3

AlexR
AlexR

Reputation: 115398

@Anthony Pegram is right. If you need such precision use BigDecimal.

Upvotes: 3

Related Questions