Rahul
Rahul

Reputation: 1667

Need different result in rounding off value in java

I am using following line of code to round off value in java

public class FloorTest 
{
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub
        System.out.println(Math.round(29.56));

        System.out.println(Math.round(27.62));

        System.out.println(Math.round(24.36));
    }

}

The output i got is 30, 28, 24. But what i want is 29, 28, 24, means only if value after point is greater than 5 round off to greater value otherwise not

Upvotes: 0

Views: 67

Answers (3)

darijan
darijan

Reputation: 9775

Now I you stated your requirement.

Then try this

Math.floor(number + 0.4);

Upvotes: 0

user3214281
user3214281

Reputation: 77

Alternative you can add 0.5 to your number and cast to int

Edit: will fail at your first example, output would also be 30

Upvotes: 2

libik
libik

Reputation: 23029

I created this method for you, but I really does not see the point of it :).

public static int roundWeirdly(double value){
    if (value - (int) value >= 0.6){
        return (int) value  + 1;
    } else {
        return (int) value;
    }
}

Upvotes: 1

Related Questions