Sometimes in Competitive programming, it is essential to print the output in a given specified format. Most users are familiar with printf function in C. Let us see discuss how we can format the output in Java:
Formatting output using System.out.printf()
This is the easiest of all methods as this is similar to printf in C. Note that System.out.print() and System.out.println() take a single argument, but printf() may take multiple arguments.
Output:
Printing simple integer: x = 600
Formatted with precison: PI = 3.14
Formatted to specific width: n = 9.2000
Formatted to right margin: n = 9324435.0000
System.out.format() is equivalent to printf() and can also be used.
Formatting using DecimalFormat class:
- DecimalFormat is used to format decimal numbers.
// Java program to demonstrate working of DecimalFormat
Output:
Without fraction part: num = 234
Formatted to Give precison: num = 234.46
appended zeroes to right: num = 234.456700
formatting Numeric part : num = 00234.46
your Formatted Dream Income : $34,456.79
Formatting dates and parsing using SimpleDateFormat class:
This class is present in java.text package.
// Java program to demonstrate working of SimpleDateFormat
Output:
Formatted Date : 20-05-2021
Parsed Date : Thu May 20 00:00:00 IST 2021