Java Reference
In-Depth Information
Because the interest amount is currency, it is desirable to display only two digits after the
decimal point. To do this, you can write the code as follows:
double amount = 12618.98 ;
double interestRate = 0.0013 ;
double interest = amount * interestRate;
System.out.println( "Interest is $"
+ ( int )(interest * 100 ) / 100.0 );
Interest is $16.4
However, the format is still not correct. There should be two digits after the decimal point:
16.40 rather than 16.4 . You can fix it by using the printf method, like this:
printf
double amount = 12618.98 ;
double interestRate = 0.0013 ;
double interest = amount * interestRate;
System.out.printf( "Interest is $%4.2f" ,
interest);
format specifier
%
4.
2 f
field width
conversion code
precision
Interest is $16.40
The syntax to invoke this method is
System.out.printf(format, item1, item2, ..., item k )
where format is a string that may consist of substrings and format specifiers.
A format specifier specifies how an item should be displayed. An item may be a numeric
value, a character, a Boolean value, or a string. A simple format specifier consists of a percent
sign ( % ) followed by a conversion code. Table 4.11 lists some frequently used simple format
specifiers.
format specifier
T ABLE 4.11
Frequent ly Used Format Specifiers
Format Specifier
Output
Example
%b
a Boolean value
true or false
%c
a character
'a'
a decimal integer
200
%d
%f
a floating-point number
45.460000
%e
a number in standard scientific notation
4.556000e + 01
%s
a string
“Java is cool”
Here is an example:
items
int count = 5 ;
double amount = 45.56 ;
System.out.printf( "count is %d and amount is %f", count, amount );
display
count is 5 and amount is 45.560000
 
 
Search WWH ::




Custom Search