For the en_US
locale:
Third = 0.333
import java.text.*;
public class IODemoThird
{
public static void main ( String[] args )
{
DecimalFormat numform = new DecimalFormat("0.000000");
System.out.println( "Third = " + numform.format(1.0/3.0) );
}
}
If you want six digits to the right of the decimal point,
use this DecimalFormat
constructor:
DecimalFormat numform = new DecimalFormat("0.000000");
The "0.000000"
is a pattern that says you want
at least one digit in the integer part of the output string,
followed by a decimal separator, followed by six digits.
Each 0
stands for one digit
in the output string.
Each zero will be replaced by a digit 0 through 9, as appropriate.
This program outputs:
Third = 0.333333
The decimal separator in the output string depends on your locale. In my US locale it is a decimal point. Even in locales where dot is not the proper decimal separator, the format string uses dot to show where the appropriate decimal separator goes. The output string will use the correct separator for the default locale. (There are methods that change this behavior, not covered here.)
All the digits of
the integer part of a number are output no matter what
the pattern of 0
s shows.
If the integer part of a number requires three digits,
all three digits will be output no matter how many 0
s in the format pattern.
This avoids producing misleading output.
What does the following fragment write?
DecimalFormat numform = new DecimalFormat("0.00"); System.out.println( "Num = " + numform.format(13.456) );