Format decimal

In this chapter you will learn:

  1. How to format decimal value
  2. How to combine formatter specifiers

Format decimal with %f

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

import java.util.Formatter;
//from  j a  va  2  s  .  c om
public class MainClass {
  public static void main(String args[]) {
    Formatter fmt = new Formatter();
    // Format 4 decimal places. 
    fmt.format("%.4f", 123.1234567); 
    System.out.println(fmt); 
  }
}

The output:

The .4 in the code above formats 4 decimal places.

Combine formatter specifiers to format both integer and decimal value

The following code combines the format specifier for integer and decimal. It also insert a character ) to display as it is.

import java.util.Formatter;
/*from  j  av a  2 s  . com*/
public class MainClass {

  public static void main(String[] args) throws Exception {
    StringBuilder buf = new StringBuilder(); // Buffer to hold output
    Formatter formatter = new Formatter(buf); // Formatter to format data into
                                              // buf
    formatter.format("%4d)%+7.2f", 2, 1234.1234);
    System.out.println(buf);

  }

}

The output:

Next chapter...

What you will learn in the next chapter:

  1. What specifier is for scientific notation format
  2. How to choose between decimal format and scientific notation
Home » Java Tutorial » String

String

    Java String type
    Java String Concatenation
    Java String Creation
    Java String Compare
    Java String Search
    Java String and char array
    Java String Conversion
    String trim, length, is empty, and substring
    String replace

StringBuffer

    StringBuffer class
    StringBuffer Insert and Append
    StringBuffer length and capacity
    StringBuffer char operation
    StringBuffer Operations
    Search within StringBuffer
    StringBuffer to String

StringBuilder

    StringBuilder
    StringBuilder insert and append
    StringBuilder length and capacity
    StringBuilder get,delete,set char
    StringBuilder delete, reverse
    StringBuilder search with indexOf and lastIndexOf
    StringBuilder to String

String Format

    Formatter class
    Format Specifier
    Format String and characters
    Format integer value
    Format decimal
    Scientific notation format
    Format octal and hexadecimal value
    Format date and time value
    Escape Formatter
    Minimum Field Width
    Specifying Precision
    Format Flags
    Uppercase Option
    Formatter Argument Index
    Align left and right
    Left and right padding a string

String Format Utilities

    Abbreviate string
    Caplitalize a string
    Uncapitalize a string
    Utility class for right padding
    Left padding
    Centers a String
    Transforms words