Java Program to Round a Number to n Decimal Places

JavaObject Oriented ProgrammingProgramming

In this article, we will understand how to round a number to n decimal places. Rounding of decimal values are done using the CEIL or FLOOR functions.

Below is a demonstration of the same −

Input

Suppose our input is −

Input : 3.1415

Output

The desired output would be −

Output : 3.2

Algorithm

Step 1 - START
Step 2 - Declare a float variable values namely my_input.
Step 3 - Read the required values from the user/ define the values
Step 4 – Use the CEIL function to round the number to the required decimal places. In this
example we are rounding up to 2 decimal places. Store the result.
Step 5- Display the result
Step 6- Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool run button.

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class DecimalFormatting {
   public static void main(String[] args) {
      float my_input;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A scanner object has been defined ");
      System.out.print("Enter the first binary number : ");
      my_input = my_scanner.nextFloat();
      DecimalFormat roundup_decimal = new DecimalFormat("#.#");
      roundup_decimal.setRoundingMode(RoundingMode.CEILING);
      System.out.println("The rounded up value of " +my_input + " is ");
      System.out.println(roundup_decimal.format(my_input));
   }
}

Output

Required packages have been imported
A scanner object has been defined
Enter the first binary number : 3.1415
The decimal number is defined as 3.1415
The rounded up value of 3.1415 is
3.2

Example 2

Here, the integer has been previously defined, and its value is accessed and displayed on the console.

import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalFormatting {
   public static void main(String[] args) {
      System.out.println("Required packages have been imported");
      double my_input = 3.1415;
      System.out.println("The decimal number is defined as " +my_input);
      DecimalFormat roundup_decimal = new DecimalFormat("#.#");
      roundup_decimal.setRoundingMode(RoundingMode.CEILING);
      System.out.println("The rounded up value of " +my_input + " is ");
      System.out.println(roundup_decimal.format(my_input));
   }
}

Output

Required packages have been imported
The decimal number is defined as 3.1415
The rounded up value of 3.1415 is
3.2
raja
Updated on 21-Feb-2022 12:39:49

Advertisements