|
-
September 27th, 2011, 04:49 PM
#1
Formatting
As a lab assignment for uni, We were given a task to write a simple program that used an infinite series to calculate pi (4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11.....)
This is what I came up with so far and it works fine!
Code:
public class Picalc
{
public static void main(String[]args)
{
int runs=20;
double total=0, series;
boolean positive=true;
System.out.println("Pi Number of Terms\n___________________________________________");
for (double x=0; x<runs; x++)
{
series = 1/(2*x+1);
if (positive)
total+= series;
else
total-= series;
positive = !positive;
System.out.println(+total*4.0+"\t\t"+(x+1));
}
}
}
<- link to console output
My problem and questions are regarding the output. Basically because of the default printing of doubles It's printing the majority with 23 decimals, is there anyway to force it to say 6 places when printing so that my column with the number of terms is lined up nicely.
Last year we programmed mainly in C, there was an easy way to do the above with the print function but as I'm still unfamiliar with Java's syntax I'm not sure if there's a simple solution to what I'm trying to do.
Is there a better way to do what I'm doing overall?
Because it's a college assignment at the start of the year I plan to keep it relatively simple but it'd be nice to trim off the rough edges.
Thanks in advance for any help!
-
September 27th, 2011, 06:37 PM
#2
Re: Formatting
Look at the DecimalFormat class and the String class's format() method.
Norm
-
September 27th, 2011, 11:30 PM
#3
Re: Formatting
You can use the String.format() method to format your output. It will take as many arguments as "objects" you want to print.
Here is an example:
Code:
double num = 2.2387654230928;
System.out.println(String.format("%2.6f%n", num));
sample output: 2.238765
The % is a format specifier, 2 is the width (number of minimum spaces fro output), .6 prints to six places after the decimal. The next % is another format specifier. The n is for a new line carriage return. Then num is the second argument that follows the first format specifiers directives. You can pass as many format strings and objects as you want.
hope it helps!
-
September 28th, 2011, 05:07 AM
#4
Re: Formatting
Sweet, that was exactly what I was looking for, implemented it and it's working nicely, thank you very much both of you.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|