Algorithm
-
Input: Take the number to be rounded (
originalNumber
) and the desired number of decimal places (decimalPlaces
). -
Multiply and Round: Multiply the
originalNumber
by 10 to the power ofdecimalPlaces
to move the decimal point to the right bydecimalPlaces
positions. 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
roundedNumber
by 10 to the power ofdecimalPlaces
to move the decimal point back to its original position.java
result = roundedNumber / Math.pow(10, decimalPlaces);
-
Output: The variable
result
now contains the original number rounded todecimalPlaces
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
#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