-2

I am trying to prevent automatic rounding off in Java. As mentioned below, I am using 2 variables which is x and y double variables.

double x = 1.05d;
double y = 2.55d;
    
System.out.println(x + y); => 3.5999999999999996

When I tried to sum these 2 variables, it gave me 3.5999999999999996 like number with higher precision. I want to prevent this behaviour without using BigDecimal. Is there any solution?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    If you can live with rounding errors, you can always use `Math.round` or format with `"%.2f"` as format specifier – knittl Oct 15 '22 at 09:26
  • @knittl I have another problem too. Assume that, this happened inside a calculating process and we are expecting 3.6. But java gives that 3.5999999. This means my logic will be runied know? – Dasun.edirisinghe Oct 15 '22 at 09:31
  • 2
    Yes, because floating point math is not exact. If you need arbitrary precision math, use `BigDecimal`. – knittl Oct 15 '22 at 09:37

1 Answers1

-1

Here is a method you can use to round double data type values to whatever precision you like. Read the comments in code:

/**
 * Will round a double data type value either Up (default) or Down with 
 * whatever desired precision.
 * 
 * @param value (double) The double data type value to round.
 * 
 * @param precision (int) The desired decimal precision. If you provide 0
 * as a precision value then there will be not decimal component, it will 
 * be 0, for example if rounding up (default) 3.5 then 4.0 will be returned. 
 * If rounding down 3.5 then 3.0 will be returned
 * 
 * @param roundDown (Optional varArgs - boolean) Default is false which 
 * tells the method to round up if the next digit after the precision is 
 * 5 or more. If true is supplied then the value is rounded down but only 
 * if the next digit after the precision is 5 or less. If next digit after 
 * precision is greater than 5 then the value is rounded up.
 * 
 * @return (double) The supplied double type value returned as a rounded 
 * double type value.
 */
public double round(double value, int precision, boolean... roundDown) {
    boolean rndDown = false;
    if (roundDown.length > 0) {
        rndDown = roundDown[0];
    }
    return java.math.BigDecimal.valueOf(value).setScale(precision,
            (rndDown ? java.math.RoundingMode.HALF_DOWN : 
                    java.math.RoundingMode.HALF_UP)).doubleValue();
}

This is how you might use the above method:

double x = 1.05d;
double y = 2.55d;
double sum = x + y;
    
System.out.println("Original Sum: " + sum);

double val = round(sum, 1);   // Precision of 1.
 
System.out.println("Rounded Sum to a precision of 1: " + val);

The Console Window should display:

Original Sum: 3.5999999999999996
Rounded Sum to a precision of 1: 3.6
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22