Output formatting in Java
Sun, 17 Nov 2024
It's very disturbing. We will learn just few common ones.
As the name suggest, it is for formatting the output before showing to user. Let's learn some:
It is similar to printf
style formatting.
Integer formatting:
%<argument_index$><flags><width><conversion>
d
= for base 10 (decimal)o
= for base 8 (octal)#
used at first, then output begins with 0.x
= for base 16 (hexadecimal)#
used at first, then output begins with 0x.int num = 1234;
int num2 = 21;
System.out.printf("%1$2d\n", num); // '1234'
System.out.printf("%1$6d %2$d\n", num, num2); // ' 1234 21'
%1$6d
:%1
: 1 means the first argument,$6
: 6 space will be taken total.d
: means integer.final int num = 2007224;
System.out.printf("%d\n", num); // 2007224
// Number with single quotes
System.out.printf("'%d'\n", num); // '2007224'
// Extra space on left
System.out.printf("%10d\n", num); // 2007224
// Extra space on right
System.out.printf("%-10d\n", num); // 2007224 //
System.out.printf("%010d\n", num); // 0002007224
// Enclose negative number in parentheses
System.out.printf("%(d\n", num); // 2007224
System.out.printf("%(d\n", -num); // (2007224)
// Number with sign
System.out.printf("%+d\n", num); // +2007224
System.out.printf("%+d\n", -num); // -2007224
Floating point number:
float
, double
, BigDecimal
.e
= for locale specific computerized scientific notationf
= for locale specific decimal formatg
= locale specific general scientific notatione
if value < 10^-4
or precision >= 10
f
if value > 10^-4
or precision < 10
System.out.printf("%f\n", 10.2); // 10.200000
// 3 digits after decimal point
System.out.printf("%.3f\n", 10.2); // 10.200
System.out.printf("%e\n", 10.2); // 1.020000e+01
// Act as e
System.out.printf("%g\n", 0.000002079); // 2.07900e-06
// Act as f
System.out.printf("%g\n", 0.207); // 0.207000
System.out.printf("%f\n", 0.000002079); // 0.000002
Character formatting
c
char ch = 'b';
// Normal printing
System.out.printf("%c\n",ch); // b
System.out.printf("%C\n",ch); // B
// using ASCII value
System.out.printf("%c\n",97); // a
// Extra space at left
System.out.printf("%5c\n",'a'); // a
// Extra space at right
System.out.printf("%-5c\n",'a'); // 'a '
Date time formatting will be discussed later
This is a comment 1.
This is a comment 2.