Hello - I have created a program which calculates the value of PI. All the calculations work well but the aim of the program is to get the user to input a number - say 7 and my program will print the value of PI to 7 decimal places.

I realise there is a DecimalFormatter and I used to 8 decimal places, for e.g.

``````// Method to format output to 8 decimal places
public static String toEightString( double quantity )
{
DecimalFormat currQuant = new DecimalFormat("#.#########");
return currQuant.format( quantity );
}``````

But this isn't feasible if the user enters 100 - Im not going to create a hundred methods like the above! So I thought of converting the value of PI, of type double, to a float and then using the formatter like below:

``````float toDP = (float)quantity;
int totalNum = numDP+1;

System.out.printf( "%totalNum.numDPf", toDP );``````

So this was suppose to print, say user enters 4, 5 numbers in total with 4 past the decimal place. But when I call it it returns an error.

So what is the best way to format the output?

Cheers

Well this

``"#.#########"``

is a String right?

So what's wrong with doing

``````StringBuilder sb = new StringBuilder("#.");
for (int i = 0; i < userInputedNumber; i++) {
sb.append("#");
}
DecimalFormat currQuant = new DecimalFormat(sb.toString());``````

Admittedly I wasn't aware of the method you outlined. It works fine but my logic seems to be somewhat incorrect in places. I know I should probably start a new post for this but does java impose a limiter on results in calculations? Like it will only show you the number to 8 decimal places?

Im asking because in my PI program, I print PI unformatted first and then formatted after, using the method above:

``````PI equals 3.1415926139392147
PI to 10 decimal places equals 3.1415926139``````

But PI equals, according to google, PI = 3.14159265. This means that rounding is occurring somewhere?