Java Reference
In-Depth Information
double interest = amount * interestRate;
System.out.println( "Interest is " + interest);
Interest is 16.404674
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, ..., itemk)
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 3.8 lists some frequently used
simple format specifiers.
format specifier
T ABLE 3.8 Frequently Used Format Specifiers
Format Specifier
Output
Example
%b
a Boolean value
true or false
%c
a character
'a'
%d
a decimal integer
200
%f
a floating-point number
45.460000
%e
a number in standard scientific notation
4.556000e ˛
+
01
%s
a string
“Java is cool”
 
Search WWH ::




Custom Search