ADS

Round Off Number To Nearest Tens

Here is a aktivitas on rounding off a number to nearest tens. For example, 35 will be rounded off to 30 and 36 to 40.

Description

The aktivitas comes with the simple logic that uses the right most digit of the given number and then identifies the nearest tens to which the number can be rounded. A number with right most digit greater than 5 will be increased to the nearest round number and with right most digit less than or equal to 5 will be decreased to the nearest round number.

As a part of the program, we will be using the mod (%) operator which gets the right most digit of the number.

 
import java.util.*;
class RoundOffNumber
{
public static void main(String args[])
{
// Create Scanner object
Scanner s=new Scanner(System.in);

// Read the number
System.out.println("Enter the number");
int n=s.nextInt();
/* Round off the number to nearest 10s */

int r=roundOffTens(n);


// Print the rounded off number
System.out.println("Rounded off to "+r);
}

public static int roundOffTens(int n)
{

// Get the right most digit
int rdigit=n%10;


// If right digit greater than 5
if(rdigit>5)
n+=10-rdigit;

// If right digit <= 5
else
n-=rdigit;

// Return the value
return n;

}

}

Sample outputs of the program

 
Enter the number
2013
Rounded off to 2010

Enter the number
25
Rounded off to 20

Enter the number
48
Rounded off to 50

Enter the number
0
Rounded off to 0

Explaining the logic of RoundOffNumber

int rdigit=n%10; This is used to get the right most digit of given number. Any number when divided by 10 gives the remainder which is equal to it's right most digit. For a single digit number the number itself is returned.

if(rdigit>5) If the right most digit is greater than 5, then
n+=10-rdigit; By this statement the value of n will become n+10-rdigit; i.e. to the number n, 10-rdigit is added. 10-rdigit gives the number which can be added to n so that the value of n will be increased to the nearest tens. For instance, consider n=48, then we get rdigit as 8 and 10-rdigit as 2. Now n+10-rdigit gives 48+2=50;

else If the right digit is not greater than 5 means it is less than or equal to 5.
n-=rdigit; The value of n will become n-rdigit. The right digit is subtracted from n. Consider 84 we get rdigit as 4 and n-rdigit gives 84-4=80;

In this way, we can round off given number to the nearest tens easily. Feel free to drop a comment.

Subscribe to receive free email updates:

ADS