-4

My source code is:

public static double roundDown(double d) {

    double value = Math.floor(d * 1e2) / 1e2;

    if(Double.toString(value).contains("."))
        return value;
    else
        return Double.parseDouble(Double.toString(value)+".00");

}

when I pass 37187.200000 then output comes 37187.19 and I want it 37187.20

ArifMustafa
  • 4,617
  • 5
  • 40
  • 48
  • Possible duplicate of [wrong answer when devide double](https://stackoverflow.com/questions/28296069/wrong-answer-when-devide-double) – Timothy Truckle Feb 06 '18 at 09:36
  • 1
    Possible duplicate of [How to round a number to n decimal places in Java](https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – ArifMustafa Feb 06 '18 at 09:37
  • This error is cause by *digital aproximation* https://en.wikipedia.org/wiki/Fixed-point_arithmetic – Timothy Truckle Feb 06 '18 at 09:45

1 Answers1

1

If you want to display two digit after decimal point, then simply you can round off like:

public static String roundDown(double d) {
    DecimalFormat f = new DecimalFormat("0.00");
    return f.format(d);
}

But if you want to store 37187.20 in variable of type "double", then it is not possible because double is stored in binary. So it is meaningless to save trailing zeros. This will remove non-significant zeros.

public static double roundDown(double d) {
    DecimalFormat f = new DecimalFormat("0.00");
    return Double.parseDouble(f.format(d));
}