0

I have such a method

    public double count(double a, double b) {
    return a + b;
}

for arguments: "111111111111111111111111111111111111111111 + 1"
Expected: 111111111111111111111111111111111111111112
Real output: 1.1111111111111112E41

how to change it?

public BigDecimal count(double a, double b) {
    BigDecimal x= BigDecimal.valueOf(a);
    BigDecimal y= BigDecimal.valueOf(b);
    return x.add(y);

} 

and for this Real output:111111111111111120000000000000000000000001.0 wtf?

Foxal
  • 23
  • 5
  • 3
    Does this answer your question? [How do I print a double value without scientific notation using Java?](https://stackoverflow.com/questions/16098046/how-do-i-print-a-double-value-without-scientific-notation-using-java) – Jordan Jan 31 '20 at 20:19
  • java `double` has about 16 significant decimal digits https://stackoverflow.com/a/13543600/2711811 - you would also find `a == count(a,1)` for your example argument. To change? see `BigDecimal`. –  Jan 31 '20 at 20:29
  • 1
    For your `BigDecimal` example - you are missing the point - when you initialize the double to what you think is a sequence of 41 1s - it is losing the signficant digits (not the magnitude) down to ~16. Your best constructing a BigDecimal from a string in your case. –  Jan 31 '20 at 20:58
  • thx Andy 1234567 – Foxal Jan 31 '20 at 21:10

1 Answers1

0

As stated in comments the double has only ~16 significant decimal digits of precision ( see https://stackoverflow.com/a/13543600/2711811 ). So this leads to this incongruity:

// 25 1's
double a = 1111111111111111111111111.;
double b = 100;
double c = (a + b);
System.out.println((a == c));  // true

In your example you're better off using BigDecimal. Here's an example:

 BigDecimal bd = new BigDecimal("111111111111111111111111111111111111111111.5");
 System.out.println(bd);
 bd = bd.add(new BigDecimal(1));
 System.out.println(bd);

prints:

111111111111111111111111111111111111111111.5
111111111111111111111111111111111111111112.5

And going back to double loses the precision:

System.out.println(bd.doubleValue());

prints:

1.1111111111111112E41

Also, if you are only working with integers then BigInteger would suffice.