gkarthiks
gkarthiks

Reputation: 501

how to round off if the value is 1.01 to 1, if 1.1 then 2 in java?

In java

How to roundoff a value(either float, bigdecimal or double) having the following pattern,

(1) If the value is 1.0, i.e., if the decimal is started with zero then this should not rounded off and the value should be the whole number. ie., in this case "1".

(2) If the value is 1.1 i.e., if the decimal place started with number greater than 0, then the whole number should be rounded to the next number. i.e., if 1.1 then it should be 2.

Upvotes: 1

Views: 3637

Answers (4)

Hoopje
Hoopje

Reputation: 12942

Your specification is not entirely clear to me. I understand your question to mean the "ceil" function, that is, 1.01 has to be rounded up, but your question can also be interpreted such that 1.01 has to be rounded down. (If the latter is what you want, look at Peter Lawrey's answer.)

For doubles (and floats) Java provides the standard method Math.ceil(double a) for the ceil function.

For BigDecimal values you can use the setScale method: set the scale to 0 (no decimal fraction) and the rounding mode to RoundingMode.CEILING to specify how to round:

static BigDecimal ceil(BigDecimal a) {
    return a.setScale(0, RoundingMode.CEILING);
}

Upvotes: 0

Jay Anderson
Jay Anderson

Reputation: 997

See https://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html. I believe RoundingMode.CEILING is what you want. BigDecimal lets you control the rounding:

new BigDecimal(1.0).setScale(0, RoundingMode.CEILING).doubleValue(); => 1.0
new BigDecimal(1.1).setScale(0, RoundingMode.CEILING).doubleValue(); => 2.0

Guava includes some utility classes for rounding floats and doubles directly with RoundingModes.

DoubleMath.roundToInt(1.0, RoundingMode.CEILING); => 1
DoubleMath.roundToInt(1.1, RoundingMode.CEILING); => 2

Edit: Whoops. I missed the part where rounding 1.01 should result in 1. The other suggested methods are more correct.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533740

So you want to round anything below 0.1 down to 0 and 0.1 or more to 1.0

 long round = Math.round(x + 0.4);

Upvotes: 5

user949300
user949300

Reputation: 15729

Try this for a start (for float and double)

int rounded = Math.round(x + 0.4);

Upvotes: 1

Related Questions