We can sometimes use this to our advantage. If we do not know how big a value might be, we can deliberately use a small field width to ensure it is printed using the exact number of print columns (no more, no less) required for printing the value.
In general, suppose the float or double value v is to be printed with the specification %w.df where w and d are integers. Firstly, the value v is rounded to d decimal places; now, suppose the number of print columns required to print v, including a possible point and a possible sign, is n. Note: There will be no point (.) if d = 0 (the value is to be rounded to a whole number).There are 2 cases to consider:
• If n is less than w (the field width is bigger): The value is padded on the left with (w ‑ n) spaces. For example, if w is 7 and the value to be printed is -3.45 so that n is 5, the number is padded on the left with (7-5) = 2 spaces and printed as ~~-3.45.
• If n is greater than or equal to w (field width is the same or smaller): The value is printed using n print columns. In this case, the field width is ignored.
As with integers, a field width is useful when we want to line up numbers one below the other. Assume we have three double variables a, b and c with values 419.563, -8.7 and 3.25, respectively. Suppose we want to print the values to 2 decimal places, lined up on the decimal point, like this:
419.56
~-8.70
~~3.25
Since the biggest number requires 6 print columns, we can line them up using a field width of at least 6. The following statements will line them up as above:
System.out.printf("%6.2f \n", a);
System.out.printf("%6.2f \n", b);
System.out.printf("%6.2f \n", c);
If we use a field width bigger than 6, the numbers will still line up but with leading spaces. For example, if we use a field width of 8, we will get (~ denotes a space)
~~419.56
~~~-8.70
~~~~3.25
Again, we can use one printf instead of three to achieve the same effect:
System.out.printf("%6.2f \n%6.2f \n%6.2f \n", a, b, c);