Tuesday, 12 September 2017

Too many decimal places when using Java?




I am currently trying to get my program to round to 2 decimal places, but seem to be unable to.
Here is my code:




double ounce;
double grams;
grams = 0.00;
System.out.println("This programme will print a table that can be used to convert ounces to grams, from values 1-15.");
System.out.println("One ounce is equal to 28.35 grams.\n\nOunces \t\t\t Grams");

ounce = 0;
do {
ounce++;
grams+=28.35;

System.out.println((""+ounce+"\t\t\t"+grams+""));
} while (ounce <15);


The output looks like this:



    Ounces           Grams
1.0 28.35
2.0 56.7
3.0 85.05000000000001

4.0 113.4
5.0 141.75
6.0 170.1
7.0 198.45
8.0 226.79999999999998
9.0 255.14999999999998
10.0 283.5
11.0 311.85
12.0 340.20000000000005
13.0 368.55000000000007

14.0 396.9000000000001
15.0 425.2500000000001


Lastly, my numbers under "grams" are not aligning exactly proper. Any ideas how to get them to align perfectly?


Answer



You can use a another output method like this:



           System.out.format("%f%5f\n",ounce, gramsFormated);



You can decide how you want your width. In this example it is 5.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...