I’ve done some searching and I cannot determine how to do what I am looking to do.
I have a method for rounding numbers which takes the paramaters numberToRound and decimalPlaces right now it is hardcoded to round to 4 decimal places but I need that to be dynamic. so if it is called with round(3.1415926536, 3) it would round to 3 decimal places rather than 4 but I cannot figure out how to get Java to take that 3 and understand that i want 000 to be printed or handled anyways.
any ideas on how to do this? Below is sample code that I have typed up but it is hard coded to 4 places since nothing I was trying would compile right
public class round
{
public static void main(String[] args)
{
System.out.println("pi rounded to 3 places is " + roundPI(3.1415926536, 3));
}
public static double roundPI(double numberToRound, int decimalPlaces)
{
numberToRound= (double)Math.round(numberToRound*10000)/10000;
return numberToRound;
}
}
current output
pi rounded to 3 places is 3.1416
I considered doing this with a math function of some kind like 10*100 to get to 1000 which would round to 3 but then if I need 4 or 5 decimal places or even 2 I still need it to figure out how to get to figure out what it needs to multiply by without hardcoding an if statement a mile long to handle if I change what im rounding to like an intrest calculator and a user decides they want it rounded to 10 or 12 or even more or less like 1 decimal place.
That will round to the correct number of places. But when you print, you also need to ensure that the right number of trailing zeroes are printed. For that, you can use
System.out.printf.