-3

I am trying to find the difference of 2 doubles with many decimal points:

double highest = 0.01518804243008679;
double lowest = 0.01464486209421528;
System.out.println("Difference: " + (highest - lowest));

And I get an answer which is correct, but is just just multiplied by 10 000:

Difference: 5.431803358715102E-4

When the desired output is:

Difference: 0.0005431803358
user8813240
  • 125
  • 1
  • 7

1 Answers1

0

There are many ways to do that. This is my solution and you can find out those ways.

package example;

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class Example {
    public static void main(String[] args) {
        double highest = 0.01518804243008679;
        double lowest = 0.01464486209421528;

        double answer = highest - lowest;
        DecimalFormat df = new DecimalFormat("#");
        df.setMaximumFractionDigits(13);
        System.out.println(df.format(answer));

        System.out.printf("Difference: %.13f\n", (highest - lowest));

        System.out.println(new BigDecimal(answer).toPlainString());

        System.out.println(String.format("%.13f", answer));
    }

}

The output is :

.0005431803359
Difference: 0.0005431803359
0.00054318033587151016983174400820644223131239414215087890625
0.0005431803359
SanduniC
  • 41
  • 5