Perry Smith

Java Questions & Answers

Home / Java Q & A Archive Page 3 / Java Q & A Archive

Format.Print class
Wednesday, 03-Feb-99 12:48:05

132.236.176.19 writes:

I'm trying to format a table so that one column has numbers with 9 decimal places and the other is in scientific notation with a 3-digit mantissa. Also both columns have to be aligned right.

Format.print(System.out,"???",a);
Format.println(System.out,"???",b);

I know this is pretty standard stuff, but I'm trying to learn JAVA on my own. Thanks
Dan


Response
Re: Format.Print class
Thursday, 04-Feb-99 21:58:59

152.172.204.192 writes:

I don't believe there's any pre-written functions you can turn to. I usually code output format myself. Maybe the tab escape sequence which is the string
"\t"
would help.

      private static final COLUMNwIDTH = 20;
      private static final DOUBLEpRECISION = 9;
      private static final MANTISSAsIZE = 3;
      String strPadCol1 = "";
      String strNumA = a.toString().trim();
      String strCol1;
      double dValA = a;
      String strPadCol2 = "";
      String strCol2 = b.toString().trim();
      double dPow;

      /* you have two options on getting 9-digit
      precision ... either by manipulating the
      string or, if Java doesn't display
      non-significant zero digits, mathematically*/

      /* mathematical method */
      /* use loop for exponentiation (since
      double exp(double) is a native method)*/
      dPow = 10;
      for (int iExp = 0; iExp < DOUBLEpRECISION;
      iExp++)
      {
      dPow**;
      }
      /* round the 'a' number to the nearest
      'DOUBLEpRECISION'ths (billionths in
      this case) place */
      dValA = ((double) (java.Math.round(dValA
      * dPow)))) / dPow;

      /* string manipulation method */
      String strIntegral;
      String strFractional;
      java.util.StringTokenizer stNumParse =
      new java.util.StringTokenizer(strNumA, ".",
      false);
      if (st.countTokens = 2)
      {
      strIntegral = st.nextToken();
      strFractional = st.nextToken();
      if (strFractional.length() > DOUBLEpRECISION)
      {
      strFractional = strFractional.substring(0,
      DOUBLEpRECISION + 1);
      }
      strNumA = strIntegral + "." + strFractional;
      }
      else
      {
      strNumA = strIntegral;
      }

      /* right-align output */
      for (int iPad = 0;
      iPad < (COLUMNwIDTH - strCol1.length());
      iPad++)
      {
      strPadCol1 = strPadCol1 + " ";
      }
      strCol1 = strPadCol1 + strNumA;

      /* do stuff here that truncates the second
      number and formats it like above */

      MikeD

Home / Java Q & A Archive Page 3 / Java Q & A Archive