Mega Code Archive

 
Categories / Java Tutorial / Development
 

Use Formatter to vertically align numeric values

import java.util.Formatter; public class Main {   public static void main(String[] argv) throws Exception {     double data[] = { 12.3, 45.6, -7.89, -1.0, 1.01 };     Formatter fmt = new Formatter();     fmt.format("%12s %12s\n", "Value", "Cube Root");     for (double v : data) {       fmt.format("%12.4f %12.4f\n", v, Math.cbrt(v));     }     System.out.println(fmt);   } } /*       Value    Cube Root      12.3000       2.3084      45.6000       3.5726      -7.8900      -1.9908      -1.0000      -1.0000       1.0100       1.0033 */