shockwave
shockwave

Reputation: 3262

Java : Rounding a decimal value to HALF_EVEN

I have been trying to write a java code to Round a value to the below requirement.

If x=63.88 => roundedValue= 64.00;

If x=63.50 => roundedValue= 64.00

If x=63.32 => roundedValue= 63.32

I tried with the different roundingModes like CEILING, DOWN, FLOOR, HALFDOWN. I also tried Math.round();

But I'm unable to get the expected output. My input is a string and output is a string.

Please find the code snippet I tried below

BigDecimal value1 = new BigDecimal(input);
value1=value1.setScale(2, RoundingMode.HALF_EVEN);
//float rounded=Math.round(amount);

String finalValue=String.valueOf(value1);

I'm unable to get the desired output. Please let me know how to achieve this?

ps: should i consider using float or BigDecimal??

Upvotes: 0

Views: 2849

Answers (4)

slartidan
slartidan

Reputation: 21566

As in your post, using BigDecimal is the way to go, if you want to use decimal rounding.

If you want to round up for numbers >= X.5 and avoid rounding for numbers < X.5 then you can use this code:

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Round {

    public static void main(String[] args) {
        System.out.println(round("63.88"));
        System.out.println(round("63.50"));
        System.out.println(round("63.32"));
    }

    private static BigDecimal round(String input) {
        BigDecimal value = new BigDecimal(input);

        BigDecimal rounded = value.setScale(0, RoundingMode.HALF_UP);
        if (rounded.compareTo(value) > 0)
            return rounded.setScale(2);

        return value;
    }

}

The output is:

64.00
64.00
63.32

Upvotes: 0

Soumitri Pattnaik
Soumitri Pattnaik

Reputation: 3556

public static void main(String args[]) {

    Double d = 63.18;
    DecimalFormat df = new DecimalFormat("00.00");

    if(d % 1 >= 0.5) 
        System.out.println(df.format(Math.round(d)));
    else 
        System.out.println(d);
}

Upvotes: 0

Vogel612
Vogel612

Reputation: 5647

What you want to do with this, is providing your own MathContext to specify the behavior of the rounding you want to perform.

The closest you will get to your current requirements is either: using RoundingMode.HALF_UP or RoundingMode.UNNECESSARY

For that you will have to use BigDecimal anyways, since Double and Float do not expose rounding.

Upvotes: 1

Mau5
Mau5

Reputation: 54

if(x%1 >= .5)
  { x = Math.round(x) }
else //do nothing

This seems like it would give you the desired output you are looking for. So if you really wanted to you could override or create your own method to call for the rounding

Upvotes: 3

Related Questions