# Rounding?!! Need help!

• 11-03-2012, 11:19 PM
aejames23
Rounding?!! Need help!
The question is
Quote:

The purpose of this method is to round integer n off to the nearest 1s, 10s, 100s, …. place. The power parameter specifies the power of 10 to be used for rounding. If power is 0, no rounding is needed (nearest 1s place), if power is 1, round to the nearest 10s place, and so on. Here are some examples:
n = 8436, power = 1  return integer is 8440
n = 8436, power = 2  return integer is 8400
n = 8436, power = 3  return integer is 8000
n = 8436, power = 4  return integer is 10000
So far i have

Code:

```        public static double round ()         {                 double n; double power; double n2;                 Scanner input = new Scanner (System.in);                 System.out.println("Enter Exponent of 10 for Rounding(0-3) ");                 power = input.nextDouble();                 System.out.println("Enter Number ");                 n = input.nextDouble();                 if ( power == 0)                 {                         System.out.println( n );                 }                 else if (power == 1)                 {                         n= Math.ceil(n * 10 + 0.5 ) / 10;                         System.out.println(n);                 }                 if (power == 2)                 {                         n = Math.ceil(n * 100 + 0.5 ) / 100;                          System.out.println(n);                 }                 else if (power == 3)                 {                         n = Math.ceil(n * 1000 + 0.5 ) / 1000;                          System.out.println(n);                 }                                                return n;         }```

I do not know how to round. Help please.
• 11-04-2012, 12:06 AM
SJF
Re: Rounding?!! Need help!
Code:

`n= Math.ceil(n / 10 ) * 10;  // Is much closer to what you're looking for.... BUT this is the CEILING not the tradition round!`
Ceiling 3.4 -> 4
Ceiling 3.5 -> 4
Ceiling 3.6 -> 4

Math (Java Platform SE 7 )
Round 3.4 -> 3
Round 3.5 -> 4
Round 3.6 -> 4
This is the round in traditional arithmetic sense... tie goes up, otherwise closest whole number.

You're still returning a double... probably want to typecast and return an int.
• 11-04-2012, 02:10 AM
pbrockway2
Re: Rounding?!! Need help!
Why all the doubles? The question only involves ints so consider code that uses ints only.

The way I would round 2153 with a power of 2 is to recognise I was dealing with hundreds. There are 21 hundreds. The remainder, 53, is "big" relative to a hundred so I would add one to make 22 hundreds. Yielding the answer, 2200.