user2999870 user2999870 - 3 years ago 254
Java Question

RoundingMode HALF_UP is not working properly

From my understand, RoundingMode.HALF_UP uses our tradition style of rounding. However, it is not giving me the desired results:

I'm using DecimalFormat() with different parameters(#, #.#, ... etc) and inputting the double 3.5545

// taken from Util
public static void setRound(int a) // Set rounding decimal places
{
roundTo = a;

String t = "#";
if (roundTo > 0)
{
t += ".";
for (int u = 1; u <= roundTo; u++)
t += "#";
}

df = new DecimalFormat(t);
df.setRoundingMode(RoundingMode.HALF_UP);
}

public static String round(double d) // Rounds up answers to set place
{
return df.format(d);
}

// taken from Testing class
for (int a = 0; a < 5; a++)
{
Util.setRound(a);
System.out.println(Util.round(3.5545));
}

// results
0 -> 4
1 -> 3.6
2 -> 3.55
3 -> 3.554 *(I want 3.555)*
4 -> 3.5545


How would I be able to fix this issue (any number trailed by 5 rounds up)?
Any help would be appreciated.

Thank you.

Answer Source

You can use BigDecimal scale method like ;

for (int i = 0; i < 5; i++) {
            BigDecimal bg = new BigDecimal("3.5545").setScale(i, RoundingMode.HALF_UP);
            System.out.println(bg);
        }

Output ;

0 --> 4
1 --> 3.6
2 --> 3.55
3 --> 3.555
4 --> 3.5545
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download