How To Format Output in Java?

0
75
Spread the love
  • 28
  • 145
  • 56
  • 35
  •  
  •  
  •  
  • 12
  •  
  •  
    276
    Shares

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
System.out.printf("$");
System.out.printf("%6.2f",price);
System.out.printf("each");

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 Character Type of output Example
d Decimal or ordinary integer %5d
%d
f fixed point or floating-point %6.3 f
%f
e E notation floating point %8.3e
%e
g general floating point %8.3g
%g
s String %12s
%s
c character %2c
%c

 

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.

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;
System.out.printf("Begin%8.2fEnd",value);
System.out.println();

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;
System.out.printf("Begin%-8.2fEnd",value);
System.out.println();

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);
System.out.println();
System.out.println("yahoo!!");

The output of the code:
$20.50 for each book
yahoo!!
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);
System.out.println();

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 $
System.out.println(myFormat.format(21.123));

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

NumberFormat myFormat=new NumberFormat.getCurrencyInstance(Locale.US)
//default formatting is $
System.out.println(myFormat.format(21.123));

The output is
$21.12

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

Different Locales that can be used as given below:

Locale Information Meaning
Locale.CANADA Canada for currency. The format is the same as the US.
Locale.CHINA China’s currency
Locale.FRANCE France’s currency
Locale.GERMANY Germany’s currency
Locale.ITALY Italy’s currency
Locale.JAPAN Japan’s currency
Locale.KOREA Korea’s currency
Locale.TAIWAN Taiwan’s currency
Locale.UK United Kingdom’s currency
Locale.US United 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);
System.out.println(value);

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.

Note

  • 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.

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

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 28
  • 145
  • 56
  • 35
  •  
  •  
  •  
  • 12
  •  
  •  
    276
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here