1. Member
Join Date
Nov 2012
Posts
5
Rep Power
0

## Rounding?!! Need help!

The question is
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

Java 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.

2. Senior Member
Join Date
Oct 2012
Posts
108
Rep Power
0

## Re: Rounding?!! Need help!

Java 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.

3. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12

## 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.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•