Java Reference
In-Depth Information
TABLE 4 . 1 :
Examples using
printf
.
printf("%d",3)
prints integer
printf("%f",3.233)
prints real number
printf("%s","abc")
prints string
printf("%c",'a')
prints character
The result will be 23.229. The reason is that the result is rounded to three decimal places
after the decimal dot. For a second example, consider the statement.
System. out . printf (
"%3d"
,23) ;
This means display the number using
at least
three characters. Therefore, “23” will be
printed. By default, the result is right justified. If we want the result to be left justified,
then we should specify a negative formatting number.
System. out . printf (
"%-10d"
,23) ;
The code will display the number 23 followed by eight spaces. Next, consider the following
example.
System. out . printf (
"%6.2f"
,23.24999) ;
This means that a real number will be printed with 2 digits after the decimal dot and at
least 6 total characters. The result will be 23.25, where there will be a single space in front
of the number. The space will guarantee that there are at least 6 characters displayed. Note
that, unlike casting, here the number is rounded. In other words, Java will display 2 digits
after the decimal dot and will try to make the output as close as possible to the original
number.
Lastly, suppose we want to display the total cost of the project, but we want to display
it in the following format:
325,365.34. Here is an example of how this can be done.
$
import
java . text .
∗
;
public class
Test
{
public static void
main(String [] args)
{
DecimalFormat myFormatter =
new
DecimalFormat(
"$###,###.00"
);
System.out. println(myFormatter. format(325365.34)) ;
}
}
The
DecimalFormat
class is defined in the
java.text.*
library. Note that if the price
of the project is 2.23, then the string
2.23 will be displayed. In other words, the symbol #
is used to represent a character only when the respective digit exits. Conversely, 0 is used to
represent a filler. For example, if the cost of the project is
$
43, then
43.00 will be printed.
$
$
Alternatively, consider the following code.
import
java . text .
∗
;
public class
Test
{
public static void
main(String [] args)
{
DecimalFormat myFormatter =
new
DecimalFormat(
"$000,000.00"
);
System.out. println(myFormatter.format(2.23));
}
}
000,002.23 when the cost of the project is 2 dollars and 23 cents.
The reason is that 0 means that 0 will be displayed if there is no digit at the specified
position.
Now the result will be
$