go to previous page   go to home page   go to next page        

Answer:

For a en_US locale:

Third = 0.333

Decimal Separator

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. A zero will be replaced by a digit 0 through 9, as appropriate. Here is a complete program.

import java.text.*;

class IODemoThird
{
  public static void main ( String[] args )
  {
    DecimalFormat numform = new DecimalFormat("0.000000"); 
    System.out.println( "Third = " + numform.format(1.0/3.0) );
  }
}

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 it goes. The output string will use the correct separator for the default locale. (There are methods that change this behavior, not covered here.)

If a big number needs more digits to the left of the decimal separator than the pattern of 0s show, they will all be output. This avoids producting misleading output.

QUESTION 9:

What does the following fragment write?

DecimalFormat numform = new DecimalFormat("0.00"); 
System.out.println( "Num = " + numform.format(13.456) );