Java Format Alternate Conversion

In this chapter you will learn:

  1. What is Java Format Alternate Conversion
  2. Syntax for Java Format Alternate Conversion
  3. Example - Java Format Alternate Conversion
  4. Example - the hexadecimal number
  5. Example - the octal number

Description

# sets alternate conversion format.

The # can be applied to %o, %x, %e, and %f.

For %e and %f, the # ensures that there will be a decimal point even if there are no decimal digits.

Syntax

fmt.format("%#f", 1.0);

Example


import java.util.Formatter;
//from  w  ww  .  j  a  v  a  2 s  . co m
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("%#f", 1.0); 
    System.out.println(fmt);
  }
}

The output:

Example 2

If you precede the %x format specifier with a #, the hexadecimal number will be printed with a 0x prefix.


import java.util.Formatter;
// w  w  w  . j  a v  a2 s.c o  m
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("%#X", 1); 
    System.out.println(fmt);
  }
}

The output:

Example 3

Preceding the %o specifier with # causes the number to be printed with a leading zero.


import java.util.Formatter;
//from  w  ww  .j a  v a  2s.  c o m
public class Main {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    fmt.format("%#o", 1); 
    System.out.println(fmt);
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What is Argument Index
  2. Syntax for Argument Index
  3. Example - Argument Index
  4. Example - Argument indexes enable you to reuse an argument without having to specify it twice
  5. Example - Relative index
  6. Example - Relative indexes are especially useful when creating custom time and date formats
Home »
  Java Tutorial »
    Java Langauge »
      Java Data Format
Java Formatter Class
Java Format Specifier
Java Format Specifier Uppercase
Java Format Precision
Java Format Flags
Java Format Justifying Output
Java Format Negative and Positive
Java Format Line up Space
Java Format Parentheses
Java Format Zero Padding
Java Format Comma
Java Format Alternate Conversion
Java Format Argument Index
Java Format date time
Java Format Date