Java Formatter format numbers

Introduction

To format an integer in decimal format, use %d.

To format a floating-point value in decimal format, use %f.

To format a floating-point value in scientific notation, use %e.

Numbers represented in scientific notation take this general form:

x.dddddde+/-yy                                                                                   

The %g format specifier makes Formatter to use either %f or %e, based on the value being formatted and the precision.

The precision is 6 by default.

The following program demonstrates the effect of the %f and %e format specifiers:

fmt.format("%f %e", 123.123, 123.123123123); 

Full source

// Demonstrate the %f and %e format specifiers. 
import java.util.Formatter; 
 
public class Main { 
  public static void main(String args[]) { 
    Formatter fmt = new Formatter(); 
 
    fmt.format("%f %e", 123.123, 123.123123123); 
    System.out.println(fmt); //from w  w  w.  ja v a  2  s  . co  m
     
    fmt.close(); 
  } 
}

To display integers in octal or hexadecimal format by using %o and %x, respectively.

For example, this fragment:

fmt.format("Hex: %x, Octal: %o", 196, 196); 

Full source

import java.util.Formatter; 
 
public class Main { 
  public static void main(String args[]) { 
    Formatter fmt = new Formatter(); 
 
    fmt.format("Hex: %x, Octal: %o", 200, 200); 
    System.out.println(fmt); //from ww w. j  a va  2s .  co m
     
    fmt.close(); 
  } 
}

To display floating-point values in hexadecimal format by using %a.

The result uses a hexadecimal significand and a decimal exponent of powers of 2.

Here is the general format:

0x1.sigpexp 

Here, sig contains the fractional portion of the significand and exp contains the exponent.

The p indicates the start of the exponent.

For example, this call:

fmt.format("%a", 512.0); 

produces this output:

0x1.0p9 

Full source


import java.util.Formatter; 
 
public class Main { 
  public static void main(String args[]) { 
    Formatter fmt = new Formatter(); 
 
    fmt.format("%a", 512.0); 
    System.out.println(fmt); /* w  w  w.j  a  v  a  2s . c  om*/
     
    fmt.close(); 
  } 
}



PreviousNext

Related