# round number to nearest integer.

Discussion in 'Java' started by Fred, Jun 5, 2004.

1. ### FredGuest

I received some help here a week ago about rounding up numbers using
Math.ceil. Unfortunately it turns out that I need to round up/down numbers
to their nearest integer.

Example 107200.01 needs to be rounded down to 107200.
107200.99 neads to be rounded up to 107201.

Is there any way to accomplish this?

Original code:

MPoriginalFormat2= (int) Math.ceil(MPoriginalFormat);

Fred, Jun 5, 2004

2. ### SudsyGuest

Fred wrote:
> I received some help here a week ago about rounding up numbers using
> Math.ceil. Unfortunately it turns out that I need to round up/down numbers
> to their nearest integer.
>
> Example 107200.01 needs to be rounded down to 107200.
> 107200.99 neads to be rounded up to 107201.
>
> Is there any way to accomplish this?
>
>
> Original code:
>
> MPoriginalFormat2= (int) Math.ceil(MPoriginalFormat);

round

public static long round(double a)

Returns the closest long to the argument. The result is rounded to
an integer by adding 1/2, taking the floor of the result, and casting
the result to type long. In other words, the result is equal to the
value of the expression:

(long)Math.floor(a + 0.5d)

Give you any ideas?

ps. There's also a method by the same name which takes a float argument
and returns an int.

Sudsy, Jun 5, 2004

3. ### Roedy GreenGuest

On Sat, 05 Jun 2004 03:59:09 GMT, "Fred" <> wrote or
quoted :

>
>Example 107200.01 needs to be rounded down to 107200.
>107200.99 neads to be rounded up to 107201.
>
>Is there any way to accomplish this?

see http://mindprod.com/jgloss/round.html

--
Coaching, problem solving, economical contract programming.
See http://mindprod.com/jgloss/jgloss.html for The Java Glossary.

Roedy Green, Jun 5, 2004
4. ### FredGuest

Thanks. I actually thought of this last night. Although I was going to
subtract .5 and then round up the result.

Simpler to use the round function though.

"Sudsy" <> wrote in message
news:...
> Fred wrote:
> > I received some help here a week ago about rounding up numbers using
> > Math.ceil. Unfortunately it turns out that I need to round up/down

numbers
> > to their nearest integer.
> >
> > Example 107200.01 needs to be rounded down to 107200.
> > 107200.99 neads to be rounded up to 107201.
> >
> > Is there any way to accomplish this?
> >
> >
> > Original code:
> >
> > MPoriginalFormat2= (int) Math.ceil(MPoriginalFormat);

>
> From the javadocs for java.lang.StrictMath:
>
> round
>
> public static long round(double a)
>
> Returns the closest long to the argument. The result is rounded to
> an integer by adding 1/2, taking the floor of the result, and casting
> the result to type long. In other words, the result is equal to the
> value of the expression:
>
> (long)Math.floor(a + 0.5d)
>
>
> Give you any ideas?
>
> ps. There's also a method by the same name which takes a float argument
> and returns an int.
>

Fred, Jun 6, 2004