Rounding off double to closest (minimum) value

72 views Asked by At

I have a method which sometimes returns 0.28 / 0.23 . I am using the below class

DecimalFormat df2 = new DecimalFormat("#.#");

but here I need this code to return me 0.2 every-time , but when its more than 0.25 its returns 0.3 by rounding it off to closet decimal .

But i want my code to return 0.2 every-time the value varies from 0.21 to 0.29. can someone help me with this ?

3

There are 3 answers

0
Reilas On BEST ANSWER

There are a few ways to accomplish this.

Casting a floating-point value to an integer will truncate the decimal.
So, you could utilize this by first multiplying by 10, truncating the value, and then re-dividing by 10.

float valueA = 0.28f;
float valueB = 0.23f;
valueA = ((int) (valueA * 10)) / 10f;
valueB = ((int) (valueB * 10)) / 10f;

Output

valueA = 0.2
valueB = 0.2

Additionally, you can utilize the BigDecimal class.
The setScale method allows you to set the amount of digits after the decimal point, in addition to setting a RoundingMode.

There are numerous types of rounding modes, see the RoundingMode JavaDoc linked above, for a table of values.

I believe you are looking for FLOOR, or DOWN, for the truncation.

Here is an example using DOWN.

BigDecimal valueA = new BigDecimal("0.28");
BigDecimal valueB = new BigDecimal("0.23");
valueA = valueA.setScale(1, RoundingMode.DOWN);
valueB = valueB.setScale(1, RoundingMode.DOWN);

Output

valueA = 0.2
valueB = 0.2

On a final note, you could just parse the value as a String and substring the value for 1 digit after the decimal point.

float valueA = 0.28f;
float valueB = 0.23f;
String stringA = String.valueOf(valueA);
valueA = Float.parseFloat(stringA.substring(0, stringA.indexOf('.') + 2));
String stringB = String.valueOf(valueB);
valueB = Float.parseFloat(stringB.substring(0, stringB.indexOf('.') + 2));

Output

valueA = 0.2
valueB = 0.2
0
Unmitigated On

You can set the RoundingMode to round down.

df2.setRoundingMode(RoundingMode.DOWN);
0
WJS On

You can also do it as follows without using DecimalFormat. To round down to the nearest 10th, just multiple by 10, casting as an int and then divide by 10d.

double[] data = {
        .21,.22,.22,.23,.24,.25,.26,.27,.28,.29
};
for (double value : data) {
    System.out.println(value + "  ->  " + ((int) (value * 10)) / 10d);
} 

prints

0.21  ->  0.2
0.22  ->  0.2
0.22  ->  0.2
0.23  ->  0.2
0.24  ->  0.2
0.25  ->  0.2
0.26  ->  0.2
0.27  ->  0.2
0.28  ->  0.2
0.29  ->  0.2