# Round Decimals

Discussion in 'Java' started by Jerry, Aug 9, 2005.

1. ### JerryGuest

I wanted to round decimals. Usually, 1.6 would be rounded to 2 and 1.4
will be rounded to 1. But I want 1.6 will be rounded to 2 and 1.4 will
also be rounded to 2; for 2.1, it will be rounded to 3 and 2.6 will be
rounded to 3. Tried to find such round function from javadoc, but was
not able to find it. Anyone knows how to round the decimals according
to the above rules?

Thanks a lot!

Jerry, Aug 9, 2005

2. ### Eric SosmanGuest

It sounds like Math.ceil() may be what you want. If
just as a collection of examples.

Eric Sosman, Aug 9, 2005

3. ### Thomas FritschGuest

Lookup the javadoc of class java.lang.Math, method ceil(double)

Thomas Fritsch, Aug 9, 2005
4. ### Patricia ShanahanGuest

Here's one way to do it:

1. Convert to java.math.BigDecimal.

2. Use setScale to round, with a specified rounding mode, either
BigDecimal.ROUND_UP or BigDecimal.ROUND_CEILING.

Up and ceiling treat negative numbers differently. Up rounds away from
zero, so -1.5 would round to -2. Ceiling rounds towards positive
infinity, so -1.5 would round to -1.

Patricia

Patricia Shanahan, Aug 9, 2005
5. ### Jeff SchwabGuest

Math.ceil() is the way to go, but just for grins:

public int roundUp(double d) {
int i = (int) d;
return d == i ? i : i + 1;
}

Jeff Schwab, Aug 9, 2005
6. ### prabhat143Guest

//let x be input value
int y = Math.floor(x+1)

prabhat

prabhat143, Aug 10, 2005
7. ### Patricia ShanahanGuest

Rounding is usually expected to preserve numbers that are already
rounded. If x is an integer, Math.floor(x+1) is x+1.

Patricia

Patricia Shanahan, Aug 10, 2005
8. ### frankgerlach22Guest

Add 0.5 to your decimal number and then convert it to an integer. This
does what you want.

frankgerlach22, Aug 12, 2005
9. ### Jeff SchwabGuest

What do you mean by "convert it to an integer?" If you convert by
casting, 1.4 will get rounded to 1, not 2. If you convert by rounding,
3.0 will get rounded to 4, not 3.

Jeff Schwab, Aug 12, 2005
10. ### frankgerlach22Guest

OK, I did not read the OP message exactly. My proposal works for
"normal" rounding. ceil() should be the right method...

frankgerlach22, Aug 12, 2005