// TestPrecision.java -- CopyLeft by tsaiwn@csie.nctu.edu.tw // to Test (1)precision, (2)computation rule for floating expression // please compare to floatdbl.c in our C/C++ handouts //Also test the format capability of the java.text.Format class //It and it's subclasses provides data editing similar to printf() in C Lang. import java.text.*; // Format, NumberFormat, DecimalFormat, ... public class TestPrecision { static final String f4dot2 = "0.00"; //Integer part at least one digit private static String myformat(float x){ DecimalFormat f = new DecimalFormat(" #######00.000####"); return f.format(x); //at least like 99.999 } private static String myformat(double x){ // rewrite for double DecimalFormat f = new DecimalFormat("########0.0000000"); return f.format(x); // the above means f.setMaximumFractionDigits(7); } private static String myfm2(double x){ DecimalFormat f = new DecimalFormat(f4dot2); f.setMinimumIntegerDigits(5); // at least 5 digits in Integer part return f.format(x); } 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="+ x); System.out.println(" (double)x="+ (double)x); System.out.println(" ===" + myformat(x) ); System.out.println("xdelta="+ myformat(xdelta)); for(i=1; i<= 8000; i++){ x = x + xdelta; /******/ } System.out.println(" After loop, x="+ x); System.out.println(" (double)x="+ (double)x); System.out.println("\nDo it again with double y ..."); y = 1234567.2; xdelta = 0.0001F; System.out.println("Before loop, y="+ y); System.out.println(" ===" + myformat(y) ); 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="+ y); System.out.println(" ===" + myformat(y) ); System.out.println(" == myfm2() has format pattern"+ " \"0.00 with modification through its method\"=="); System.out.println(" which means %4.2f in C Language"); System.out.println(" myfm2(123.564)=" + myfm2(123.564) ); System.out.println(" myfm2(123.566)=" + myfm2(123.566) ); System.out.println(" myfm2(123.565)=" + myfm2(123.565) ); System.out.println(" 注意不是真的四捨五入, 這符合IEEE754的規定"); System.out.println("3849==="+ new DecimalFormat("##000000").format(3849)); } }