Algorithm
-
Input: Take the number to be rounded (
originalNumber) and the desired number of decimal places (decimalPlaces). -
Multiply and Round: Multiply the
originalNumberby 10 to the power ofdecimalPlacesto move the decimal point to the right bydecimalPlacespositions. Use theMath.round()function to round the result to the nearest integer.java
multipliedNumber = originalNumber * Math.pow(10, decimalPlaces); roundedNumber = Math.round(multipliedNumber); -
-
Divide: Divide the
roundedNumberby 10 to the power ofdecimalPlacesto move the decimal point back to its original position.java
result = roundedNumber / Math.pow(10, decimalPlaces); -
Output: The variable
resultnow contains the original number rounded todecimalPlacesdecimal 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
#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
Demonstration
Java Programing Example to Round a Number to n Decimal Places-DevsEnv