How To Format Output in Java?

How To Format Output in Java?

Java uses the following methods to display output

  • print()
  • println()
  • printf()

The method printf() works on the formatting part of the java. Formatting an output can be further divided into two parts. They are as follows:

  • NumberFormat
  • DecimalFormat

printf() method allows us to add formatting instructions that specify such things. The format String in a printf() call does noit change the way a number is stored internally for calculation. All the format string does, is create a nice looking bunch of digit characters that can be displayed on our screen.

lets check with an example:

double price=20.5

The output will be $20.50 each

  • The first argument to printf() method is the format specifier String.
  • The second argument is the number or some other value that needs to be formatted and provide output.
  • %6.2f tells us that output will be a floating-point number in a field. where the number of space width will be 6(that is there will be space for 6 characters).
  • .2 signifies that after a decimal point there will be 2 digits.
  • % stands for format specifier.

The above could have been written as

double price=20.5
System.out.printf("$%6.2f each",price);

The output will be $20.50 each
The format specifier supports the below types

  • Decimal
  • fixed point or floating-point
  • E notation
  • general floating point
  • String
  • character

The table below will give more clarity:

Conversion CharacterType of outputExample
dDecimal or ordinary integer%5d
ffixed point or floating-point%6.3 f
eE notation floating point%8.3e
ggeneral floating point%8.3g


So the first number specifies (%6.3f)the total number of spaces used to output the value. If that number is larger than the spaces needed for the output, extra blanks are added to the beginning of the output value.

See also  Abstract Class Format in Java

If that number is smaller than the number of spaces needed for the output value, enough extra spaces are added to accommodate the output value, irrespective of the space specified.

For String s and Character c formats, we can include only one number that can specify the field width for the output value. Like %20s,%5c. If no number is given, the value is output with no leading or trailing blank spaces.

Right Justified format

When the value output does not fill the field width, we specified, blanks are added in front of the value output. The output is known as the right-justified format.

double price=20.123;

The output of the code
Begin   20.12End

Left Justified format

When the value output does not fill the field width, we specified, and we add a hyphen after the % any extra blank space is placed after the value output. This type of formatting is known as left-justified.

double price=20.123;

The output of the code
Begin20.12   End

printf() method can take more arguments(any number of arguments). The first argument is always the format string argument followed by any additional arguments.

let us see an example:

double price=20.5;
String item="book";
System.out.printf("$%6.2f for each %s",price,item);

The output of the code:
$20.50 for each book
You can also add a new line in the formatting output string as well.

double price=20.5;
String item="book";
System.out.printf("$%6.2f for each %s",price,item);

can be written as

double price=20.5;
String item="book";
System.out.printf("$%6.2f for each %s \n",price,item);

Note: It is legal to escape character sequence ‘\n’ to indicate a new line but it is good to use ‘\n’.The best approach is to use ‘%n’ The prime reason for not using ‘\n’as it is system dependent but ‘%n’ is system independent.

There are also different approaches to money formatting. We can use class NumberFormat for this purpose. We need to import java.text.NumberFormat package into our code.

NumberFormat myFormat=new NumberFormat.getCurrencyInstance()
//default formatting is $

The output is
However, you can also specify the locale information as an argument.

NumberFormat myFormat=new NumberFormat.getCurrencyInstance(Locale.US)
//default formatting is $

The output is

See also  What is a Compilation Unit in Java?

For locale, we need to import java.util.Locale class into our code.

Different Locales that can be used as given below:

Locale InformationMeaning
Locale.CANADACanada for currency. The format is the same as the US.
Locale.CHINAChina’s currency
Locale.FRANCEFrance’s currency
Locale.GERMANYGermany’s currency
Locale.ITALYItaly’s currency
Locale.JAPANJapan’s currency
Locale.KOREAKorea’s currency
Locale.TAIWANTaiwan’s currency
Locale.UKUnited Kingdom’s currency
Locale.USUnited States’s currency


The Decimal class Format

For working with the decimal format we need to import java.text.DecimalFormat class. An object of the class DecimalFormat has a number of different methods that can be used to produce numerical Strings in various formats.

The syntax:

DecimalFormat formatter=new DecimalFormat(pattern);

An example:

DecimalFormat formatter=new DecimalFormat("000.000");

The format() method of the class DecimalFormat can be used to convert a floating-point number, such as one of type double, to a corresponding numerical String following the pattern used to create the DecimalFormat object.

DecimalFormat_Object(formatter here).format(Double_expression);

This returns a String value for a String representation of the value of Double_expression.

DecimalFormat formatter=new DecimalFormat("000.000");
String value=formatter.format(12.23456789);

The output is 012.346
The format of the string produced is determined by the pattern string that was used as the argument to the constructor that created the object of the class DecimalFormat.


  • The result is rounded when the number of digits is less than the number of digits available in the number being formatted.
  • If the format pattern is not consistent with the value of the number, such as a pattern that asks for the digits before the decimal point for a number such as 567.893 then the format rules are violated so that no digits are lost.
  • The pattern can specify the exact number of digits before and after the decimal or it can specify minimum numbers of digits.
  • In a pattern, the character ‘0’ is used to represent a required digit and the character ‘#’ is used to indicate an optional digit.
  • # is the optional digit. It is only shown if it is a non zero digit and is not shown if it is a zero digit.
  • The ‘#’ optional digits should go where zero placeholders would appear in a numeral string, in other words, any ‘#’ optional digits precede the zero digits, ‘0’ before the decimal point in the pattern and any ‘#’ optional digits follow the zero digits ‘0’ after the decimal point in the pattern.
  • It is good to use a pattern as “#00.00##” but not “0##.##00” or any such combinations.
  • ‘%’ (character percentage) placed at the end of the pattern indicates that the number is to be expressed as a percentage. The % causes the number to multiplied by 100 and appended a percentage (%) sign.
  • E notation is specified by indicating an ‘E’ in the pattern string. Example- “00.###E0” says two digits before decimal point then 3 or fewer digits after the decimal point.
  • The mantissa is the decimal number before E, The minimum number of significant digits in the mantissa (that is the sum of the number of digits before and after the decimal point) is the minimum of the number of the digits indicated before the decimal point plus the maximum of the number of the digits indicated after the decimal point.
See also  Abstract Class URLStreamHandler in Java

For example, “##0.0##” indicates that one, two or three digits before the decimal point and one, two or three digits after the decimal.

An example:

import static java.lang.System.out;
class UserAccount{
public static void main(String[] args)

Note -When we are directly importing static java.lang.System.out, we can not use System.out.println(); Refer here for the explanation.

Share and Enjoy !

6 thoughts on “How To Format Output in Java?

  1. Everything published was actually very logical. But,
    what about this? what if you added a little content? I ain’t saying your content is not solid., however what
    if you added a title that grabbed folk’s attention? I mean How To
    Format Output in Java? – Tech Travel Hub is
    kinda plain. You could glance at Yahoo’s front page and watch
    how they create post headlines to get viewers to open the links.
    You might add a related video or a pic or two to
    grab people excited about everything’ve written. In my opinion, it could bring your
    posts a little livelier.

  2. Does your site have a contact page? I’m having problems locating it but, I’d
    like to shoot you an email. I’ve got some recommendations for your blog
    you might be interested in hearing. Either way, great blog
    and I look forward to seeing it grow over time.

  3. Pingback: Homepage
  4. each time i used to read smaller articles which as well clear their
    motive, and that is also happening with this paragraph which I
    am reading now.

  5. Nice read, I just passed this onto a friend who was doing some research on that. And he just bought me lunch because I found it for him smile So let me rephrase that: Thank you for lunch!

  6. Howdy! Do you use Twitter? I’d like to follow you if that would be okay. I’m undoubtedly enjoying your blog and look forward to new posts.

Leave a Reply

Your email address will not be published. Required fields are marked *