Java NumberFormat/DecimalFormat example 

Joined:
04/09/2007
Posts:
710

January 07, 2010 20:02:00    Last update: January 07, 2010 20:07:19
If all you want is a quick way to format some numbers, a sample program speaks more words than the full documentation.
import java.text.DecimalFormat;

public class TestNumberFormat {
    public static void main(String[] args) throws Exception {
        double[] n = { 1, 12.0, 123.9, 123.456, 123E5, 123E-5 };

        // 0 represents 1 digit
        DecimalFormat f = new DecimalFormat("00.00");
        System.out.println("Formatting with 0.00");
        for (int i = 0; i < n.length; i++) {
            System.out.println(n[i] + ": " + f.format(n[i]));
        }

        // # is one digit, but can be omitted if it is 0
        f = new DecimalFormat("#0.0#");
        System.out.println("\nFormatting with #0.0#");
        for (int i = 0; i < n.length; i++) {
            System.out.println(n[i] + ": " + f.format(n[i]));
        }

        // prefixes and suffixes can be added
        // befause # is special character, it is enclosed between ' s
        f = new DecimalFormat("$#0.0# m/s'#'");
        System.out.println("\nFormatting with $#0.0 m/s'#'");
        for (int i = 0; i < n.length; i++) {
            System.out.println(n[i] + ": " + f.format(n[i]));
        }

        // grouping separators can be added 
        f = new DecimalFormat("$#,##0.00");
        System.out.println("\nFormatting with $#,##0.00");
        for (int i = 0; i < n.length; i++) {
            System.out.println(n[i] + ": " + f.format(n[i]));
        }
    }
}


Use String.format:
public class TestFormat {
    public static void main(String[] args) {
        int a = 1;
        float b = 2;
        double c = 3.4354365;
        long d = 43241;

        // use precision 2, minimum width 5 
        System.out.println(String.format("%1$5d, %2$5.2f, %3$5.2f, %4$5d", a, b, c, d));
    }
}
Share |
| Comment  | Tags
 
Easy email testing with http://www.ximailstop.com