Programming/Java
DecimalFormat
halatha
2011. 4. 5. 06:43
import java.text.DecimalFormat; // http://stackoverflow.com/questions/1899138/formatting-strings-in-java // http://www.coderanch.com/t/417160/java/java/cut-double-decimal-point // http://www.javaservice.net/~java/bbs/read.cgi?m=devtip&b=javatip&c=r_p&n=931308733 // http://www.javaservice.net/~java/bbs/read.cgi?m=devtip&b=javatip&c=r_p&n=920434490 // 유효숫자의 개수에 따라 소수점 위와 아래의 표현할 수 있는 숫자의 개수가 달라짐 // e.g. 소수 이하의 자리수를 유효숫자 2자리까지 필요하다면 // 그 수치는 70조(70,368,744,177,663.99)까지 public class TestDecimalFormat { public static void printDFNum(double d) { System.out.printf("double %%f\t%f\n", d); System.out.printf("double %%g\t%g\n", d); System.out.printf("double %%G\t%G\n", d); DecimalFormat[] dfArray = { new DecimalFormat("0.#"), new DecimalFormat("0.##"), new DecimalFormat("0.###"), new DecimalFormat("0.####"), new DecimalFormat("0.#####"), new DecimalFormat("0.######"), new DecimalFormat("0.#######"), new DecimalFormat("0.##############################"), new DecimalFormat("0.#E0"), new DecimalFormat("0.##E0"), new DecimalFormat("0.###E0"), new DecimalFormat("0.####E0"), new DecimalFormat("0.#####E0"), new DecimalFormat("0.######E0"), new DecimalFormat("0.#######E0"), new DecimalFormat("0.##############################E0"), }; for ( DecimalFormat df : dfArray ) System.out.println(df.getMaximumFractionDigits() + "\t" + df.format(d)); } public static void main(String[] args) { double[] dArray = { 2480965783.760506D, 6155191220190383100.123456D, 6.155191220190383100123456E18 }; System.out.println("Double.MAX_VALUE\t" + Double.MAX_VALUE); for ( double d : dArray ) printDFNum(d); } }