1

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?

3
  • 5
    A double doesn't have the level of precision you need. Not enough significant digits. Commented Feb 9, 2012 at 14:34
  • @AnthonyPegram - make that an answer, not a comment, because you are correct. Commented Feb 9, 2012 at 14:36
  • @AnthonyPegram - and also provide an alternative. Commented Feb 9, 2012 at 14:41

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

Just curious, but why is he getting a BIGGER result than expected? Does the lack of precision result in a rounding error?
Yes, lack of precision result. The double type is available to represent any 32-bit integer, but when it goes beyond this, the precision is less although you can represent some certain very big values.
0

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

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.