How to format a string using fixed-width fields in Java

4 Answers

0 votes
/**
Common format specifiers
-----------------------------------
%-10s   // Left-aligned string, width 10
%10s    // Right-aligned string, width 10
%5d     // Integer, width 5
%08d    // Integer, width 8, padded with zeros
%12.2f  // Floating-point, width 12, 2 decimal places
*/

public class FixedWidthFields {

    /**
     * Formats a record using fixed-width fields.
     *
     * %-15s = left-aligned string with width 15
     * %10d  = right-aligned integer with width 10
     * %12.2f = right-aligned decimal number with width 12
     *          and 2 digits after the decimal point
     */
    public static String formatRecord(String name, int age, double salary) {
        return String.format("%-15s%10d%12.2f",
                             name, age, salary);
    }

    public static void main(String[] args) {

        // Store the formatted string in a variable
        String result = formatRecord("Six", 60, 125000.0);

        System.out.println(result);
    }
}


/*
run:

Six                    60   125000.00

*/

 



answered Oct 18 by avibootz
edited Oct 18 by avibootz
0 votes
public class FixedWidthString {
    public static void main(String[] args) {

        // Left-align "Hello" in a field 10 characters wide
        String result = String.format("%-10s", "Hello");

        System.out.println("|" + result + "|");
    }
}


/*
run:

|Hello     |

*/

 



answered Oct 18 by avibootz
0 votes
public class ZeroPadding {
    public static void main(String[] args) {

        // Pad with leading zeros to width 8
        String result = String.format("%08d", 123);

        System.out.println(result);
    }
}


/*
run:

00000123

*/

 



answered Oct 18 by avibootz
0 votes
public class TableExample {
    public static void main(String[] args) {

        System.out.printf("%-15s%-10s%-12s%n",
                          "Name", "Age", "Salary");

        System.out.printf("%-15s%-10d%-12.2f%n",
                          "Viola", 30, 85000.0);

        System.out.printf("%-15s%-10d%-12.2f%n",
                          "Tom", 42, 92000.0);
    }
}


/*
run:

Name           Age       Salary      
Viola          30        85000.00    
Tom            42        92000.00    

*/

 



answered Oct 18 by avibootz
...