// TestFormat.java -- CopyLeft by tsaiwn@csie.nctu.edu.tw // to test the format capability of the java.text.Format class import java.text.*; // Format, NumberFormat, DecimalFormat, ... public class TestFormat { static final String myformat = "0.00"; //Integer part at least one digit private static String myfmt(double x, int t, int p){ DecimalFormat s = new DecimalFormat("##############0.0######"); s.setMaximumFractionDigits(p); s.setMinimumFractionDigits(p); int n = t - p - 1; if(n<0) n=1; // one position for decimal point s.setMaximumIntegerDigits(n); // %t.pf s.setMinimumIntegerDigits(1); // at least 1 digits in Integer part String ans = s.format(x); while(ans.length() < t) ans = " "+ans; return ans; } private static String myfmt(double x, int t){ return myfmt(x, t, 0); } private static String myfmt(double x){ return myfmt(x, 15, 6); // use %15.6f } public static void main( String p[]) { float x, xdelta; double y; long i; x = (float)1234567.2; xdelta = 0.0001f; System.out.println("Before loop, x="+ myfmt(x,14,5)); // %14.5f System.out.println(" (double)x="+ myfmt((double)x,14,5)); System.out.println("xdelta="+ myfmt(xdelta,9,5)); // %9.5f for(i=1; i<= 8000; i++){ x = x + xdelta; /******/ } System.out.println(" After loop, x="+ myfmt(x,14,5)); System.out.println(" (double)x="+ myfmt(x,14,5)); System.out.println("\nDo it again with double y ..."); y = 1234567.2; xdelta = 0.0001F; System.out.println("Before loop, y="+ myfmt(y,14,5)); for(i=1; i<= 8000; i++){ y = y + xdelta; /*** promotion is allowed, not coercion ***/ } /*** x = y; is not allowed ! ***/ System.out.println(" After loop, y="+ myfmt(y,14,5)); System.out.println(" ="+ myfmt(y,14)); System.out.println(" ="+ myfmt(y)); System.out.println(" myfmt(12345, 7)=" + myfmt(12345, 7) ); System.out.println("3849==="+ new DecimalFormat("##000000").format(3849)); } }