Java program to round a number to n decimal places
httw//:spww.theitroad.com
Here's an example Java program that rounds a number to n decimal places:
public class RoundNumber { public static void main(String[] args) { double num = 3.14159265358979323846; int n = 3; double rounded = round(num, n); System.out.println("Original number: " + num); System.out.println("Rounded number: " + rounded); } public static double round(double num, int n) { double factor = Math.pow(10, n); return Math.round(num * factor) / factor; } }
This program first initializes a variable num
with the original number to be rounded, and a variable n
with the number of decimal places to round to. The program then calls a round()
method with the input number and decimal places as arguments.
The round()
method first calculates a scaling factor by raising 10 to the power of the number of decimal places. The input number is then multiplied by this factor, rounded to the nearest integer using the Math.round()
method, and then divided by the factor to obtain the rounded number.
The program then prints the original and rounded numbers to the console.
The output of this program would be:
Original number: 3.141592653589793 Rounded number: 3.142