Skip to content
Advertisement

Java – rounding double to 2 decimal places

I know this question has been asked many times but I’m stuck and I don’t know what the correct solution should be. I’m writing a program and there’s a lot of numbers multiplication. The result must be rounded to 2 decimal places but sometimes the result is not correct.

For example: I have two doubles v1=99.338 and v2=732.5.

I want to multiply them and have the result rounded to 2 decimal places. The correct result is 72765.085 so after rounding it should be 72765.09 however in computer the result is 72765.08499999999 and all the rounding methods give 72765.08 which is obviously wrong.

For example

double x= v1 * v2; //x=72765.08499999999

    DecimalFormat dec= new DecimalFormat("0.00");
    decsetRoundingMode(RoundingMode.HALF_UP);
    String v = dec.format(x);

gives 72765.08. The RoundingMode.CEILING in this example works OK but with other values for v and v2 is wrong.

NumberFormat nf= NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.format(x);

gives 72765.08.

BigDecimal big = new BigDecimal(x, setScale(2, RoundingMode.HALF_UP);
double v = decWartosc.format(x);

gives v=72765.08. Any other ideas?

I’ve tried this in C# and the result is correct.

Advertisement

Answer

You must use BigDecimal for the calculation itself.

BigDecimal exact = BigDecimal.valueOf(v1).multiply(BigDecimal.valueOf(v2));
BigDecimal big = exact.setScale(2, RoundingMode.HALF_UP);
System.out.println(big.toString());
Advertisement