Consider the following code segment.
Scanner sc = new Scanner (System.in);
int num_item = sc.nextInt();
double price_perunit = sc.nextDouble();
double charge = num_item * price_perunit;
System.out.println("Total price = " + ": RM" + charge);
What is the output if num_item is 2 and price_perunit is 2.50?
Suppose we want the answer to be RM5.00 but the output we get is RM5.0. Why?
To correct the code, we need to use DecimalFormat class.
The output statement should be like this;
DecimalFormat myformat = new DecimalFormat("0.00");
System.out.println("Total price = " + ": RM" + myformat.format(charge));
Try compile and run your program to see the output.
Note that to use DecimalFormat, you will need to add import java.text.DecimalFormat; at the top of your program, so that the compiler understands what you mean by it. If you forget this, you will get a compiler error ``cannot resolve symbol''.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Price{
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int num_item = sc.nextInt();
double price_perunit = sc.nextDouble();
double charge = num_item * price_perunit;
DecimalFormat myformat = new DecimalFormat("0.00");
System.out.println("Total price = " + ": RM" + myformat.format(charge));
}
}
We can also use printf statement in Java programming. (printf is a C language keyword and usually used in C programming) .
The printf method is part of the java.io.PrintStream class and provides String formatting similar to the printf() function in C.
Example:
System.out.printf("Hello %s!%n", "World");
Copy
The output from the above statement will be;
Hello World!
To break the string into separate lines, we have a %n specifier:
System.out.printf("baeldung%nline%nterminator");
Copy
The code segment above will produce the following output:
baeldung
line
terminator
Copy
The %n separator printf() will automatically insert the host system's native line separator.
To format Boolean values, we use the %b format.
According to the docs, it works the following way: if the second argument is null, then the result is “false”. If the argument is a boolean or Boolean, then the result is the string returned by String.valueOf(arg). Otherwise, the result is “true”.
So, if we do the following:
System.out.printf("%b%n", null);
System.out.printf("%B%n", false);
System.out.printf("%B%n", 5.3);
System.out.printf("%b%n", "random text");
then we'll see:
false
FALSE
TRUE
true
To format a simple string, we'll use the %s combination. Additionally, we can make the string uppercase:
printf("'%s' %n", "java");
printf("'%S' %n", "java");opy
And this is the output:
'java'
'JAVA'
Copy
Also, to specify a minimum length, we can specify a width:
printf("'%15s' %n", "java");
Copy
which gives us:
' java'
Copy
If we need to left-justify our string, we can use the – flag:
printf("'%-10s' %n", "java");Copy
and the output will be:
'java '
Copy
Even more, we can limit the number of characters in our output by specifying a precision:
System.out.printf("%2.2s", "Hi there!");
Copy
The first x number in %x.ys syntax is the padding. y is the number of chars.
For our example here, the output is Hi.
The result of %c is a Unicode character:
System.out.printf("%c%n", 's');
System.out.printf("%C%n", 's');
Copy
The capital letter C will uppercase the result:
s
S
Copy
But if we give it an invalid argument, then Formatter will throw IllegalFormatConversionException.
printf also can be used to display the numerical datatype. However, it's only valid for certain data types. Here are some common ones:
s formats strings.
d formats decimal integers.
f formats floating-point numbers.
t formats date/time values.
Example:
System.out.println("1234567890123456789");
System.out.printf("%10d\n",56342);
System.out.printf("%3d\n", 56342);
The output:
1234567890123456789
56342
56342
The printf() method accepts all the integers available in the language — byte, short, int, long, and BigInteger if we use %d:
System.out.printf("simple integer: %d%n", 10000L);
Copy
so, the output will be:
simple integer: 10000
Copy
In case we need to format our number with the thousands separator, we can use the , flag. And we can also format our results for different locales:
System.out.printf(Locale.US, "%,d %n", 10000);
System.out.printf(Locale.ITALY, "%,d %n", 10000);
Copy
As we can see, the formatting in the US is different than in Italy:
10,000
10.000
Example to format a float number, we need to use character f .
System.out.printf("%f", 5.1473);
Copy
which will output:
5.147300
Of course, the first thing that comes to mind is to control the precision:
System.out.printf("'%5.2f'%n", 5.1473);
Copy
Here we define the width of our number as 5, and the length of the decimal part is 2:
' 5.15'
Copy
Here we have one-space padding from the beginning of the number to support the predefined width.
To have our output in scientific notation, we just use the e conversion-character:
System.out.printf("'%5.2e'%n", 5.1473);
And this is our result:
'5.15e+00'
Example:
System.out.printf("To print integer number %d", 5);
System.out.printf("To print floating number %f", 5.0);
The output will be;
To print integer number 5To print floating number 5.000000
Example:
System.out.printf("To print integer number %d \n", 5);
System.out.printf("To print floating number %f", 5.0);
The output will be;
To print integer number 5
To print floating number 5.000000
Note: Use the 'next line' tab '\n' to separate the output into two different lines.
Example:
int a = 50;
System.out.printf("To print integer number %d \n", a);
System.out.printf("To print floating number with two decimal point, ");
System.out.printf("%.2f", 5.0);
The output will be;
To print integer number 50
To print floating number with two decimal point, 5.00
Copy
For date and time formatting, the conversion string is a sequence of two characters: the t or T character and the conversion suffix.
Let's explore the most common time and date formatting suffix characters with examples.
Definitely, for more advanced formatting, we can use DateTimeFormatter, which has been available since Java 8.
First, let's see the list of some useful suffix characters for time formatting:
H, M, S characters are responsible for extracting the hours, minutes and seconds from the input Date.
L, N represent the time in milliseconds and nanoseconds accordingly.
p adds a.m./p.m. formatting.
z prints out the time-zone offset.
Now, let's say we want to print out the time part of a Date:
Date date = new Date();
System.out.printf("%tT%n", date);
Copy
The code above along with %tT combination produces the following output:
13:51:15
Copy
In case we need more detailed formatting, we can call for different time segments:
System.out.printf("hours %tH: minutes %tM: seconds %tS%n", date, date, date);
Copy
Having used H, M and S, we get this result:
hours 13: minutes 51: seconds 15
Copy
However, listing date multiple times is a pain.
Alternatively, to get rid of multiple arguments, we can use the index reference of our input parameter, which is 1$ in our case:
System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", date);
Copy
Here we want as an output the current time, a.m./p.m., the time in milliseconds and nanoseconds, and the time-zone offset:
13:51:15 pm 061 061000000 +0400
Like time formatting, we have special formatting characters for date formatting:
A prints out the full day of the week.
d formats a two-digit day of the month.
B is for the full month name.
m formats a two-digit month.
Y outputs a year in four digits.
y outputs the last two digits of the year.
Suppose we want to show the day of the week, followed by the month:
System.out.printf("%1$tA, %1$tB %1$tY %n", date);
Copy
Then, using A, B and Y, we'd get this output:
Thursday, November 2018
Copy
To have our results all in numeric format, we can replace the A, B, Y letters with d, m, y:
System.out.printf("%1$td.%1$tm.%1$ty %n", date);
Copy
which will result in:
22.11.18
What would the following print out?
DecimalFormat fmt1 = new DecimalFormat("0.000E0");
DecimalFormat fmt2 = new DecimalFormat("0.0##");
System.out.println ( fmt1.format(0.1) ); // (a) System.out.println ( fmt1.format(3.14159) ); // (b) System.out.println ( fmt2.format(1.5) ); // (c) System.out.println ( fmt2.format(0.0009) ); // (d) System.out.println ( fmt2.format(2.7e3) ); // (e)
Note: Write a simple program to see the output.
Your test program will need to import java.text.DecimalFormat.