Rounding off a number to nearest multiple of 10

Today we will see how to round off a number to the nearest multiple of 10 in Java.

Example:

13 will be rounded off to 10.

27 will be rounded off to 30.

55 will be rounded off to 50.

 

The logic which we will use is to take the modulus of the number and then find its distance with 10, and then use this result to get the nearest multiple of 10.

If the number is 22.
Then modulus of 22 with 10 is 2.
Since 2 is less than 5, we will subtract 2 from 22, which will give us 20.

If the number is 38.
Then modulus of 38 with 10 is 8.
Since 8 is greater than 5 we will subtract 8 from 10, which will give us 2.
We will then add this 2 to 38 which will give us 40.

Round off a number to the nearest multiple of 10 in Java

Okay now let’s get straight to the code.

import java.util.Scanner;
public class test
{

  public static void main(String[] args)
  { 
   Scanner sc=new Scanner(System.in);
   System.out.println("Enter number");
   int n=sc.nextInt();
   int rem;
   rem=n%10;
   
   if(rem>5)
   {
     n=n+(10-rem);
   }
   else
   {
    n=n-rem; 
   }
   System.out.println("Result is: "+ n);
  } 
}

Okay now, let’s run our program and see what we get.

Enter number
87
Result is = 90
Enter number
75
Result is = 70
Enter number
112
Result is = 110

Though this program may seem simpler this logic is asked many times in interviews.

Hope this helped you out.

Have a nice day ahead.

Also Read:

Implementation of PCA reduction in Python

Sum of elements in an Array in Java

Leave a Reply

Your email address will not be published. Required fields are marked *