Algorithm


  1. Input: Take the number to be rounded (originalNumber) and the desired number of decimal places (decimalPlaces).

  2. Multiply and Round: Multiply the originalNumber by 10 to the power of decimalPlaces to move the decimal point to the right by decimalPlaces positions. Use the Math.round() function to round the result to the nearest integer.

    java
    multipliedNumber = originalNumber * Math.pow(10, decimalPlaces);
    roundedNumber = Math.round(multipliedNumber);
  3.  
  4. Divide: Divide the roundedNumber by 10 to the power of decimalPlaces to move the decimal point back to its original position.

    java
    result = roundedNumber / Math.pow(10, decimalPlaces);
     
  5. Output: The variable result now contains the original number rounded to decimalPlaces decimal places.

 

Code Examples

#1 Code Example- Round a Number using format

Code - Java Programming

public class Decimal {

    public static void main(String[] args) {
        double num = 1.34567;

        System.out.format("%.4f", num);
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
1.3457

#2 Code Example- Round a Number using DecimalFormat

Code - Java Programming

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class Decimal {

    public static void main(String[] args) {
        double num = 1.34567;
        DecimalFormat df = new DecimalFormat("#.###");
        df.setRoundingMode(RoundingMode.CEILING);

        System.out.println(df.format(num));
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
1.346
Advertisements

Demonstration


Java Programing Example to Round a Number to n Decimal Places-DevsEnv