/* Format.java
 * Copyright (C) 1996 by William Giel
 *
 * E-mail: rvdi@usa.nai.net
 * WWW: http://www.nai.net/~rvdi/home.htm
 *
 ***************************************************************************
 * Abstract
 * --------
 * This unit provides a method to convert doubles to a String, formatted to a
 * desired level of precision.
 ***************************************************************************
 * Permission to use, copy, modify, and distribute this software and its
 * documentation without fee for NON-COMMERCIAL purposes is hereby granted.
 * 
 * THE AUTHOR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY
 * OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. THE AUTHOR SHALL NOT BE LIABLE
 * FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 ***************************************************************************/

import java.lang.*;

public class Format
{
	StringBuffer buf;
	
	Format(double d, int prec)
	{
		//Default is positive number
		boolean negative=false;
		
		//Round off our number
		d= ((double)Math.round(d * Math.pow(10,prec)))/Math.pow(10,prec);

		//If negative, set our flag and add a space to len for a minus sign
		if(d<0){
			negative=true;
			d=Math.abs(d);
		}

		//Separate the whole and fractional parts of our number
		long wholeNum=(long)d;
		double frac=d-(double)wholeNum;

		//Create the StringBuffer
		buf=new StringBuffer();

		//If our negative flag is true, place the minus sign.
		if(negative)buf.append('-');

		//Append the whole number portion
		buf.append(wholeNum);

		//Now we'll work on the fractional part, first appending the
		//decimal point, converting to a whole, then running the same
		//routine as above.
		if(prec>0){
			buf.append('.');
			wholeNum=(long)(frac * Math.pow(10,prec));
			while(--prec>=0){
				int digit=(int)(wholeNum / (long)Math.pow(10,prec));
				wholeNum-=(long)digit * (long)Math.pow(10,prec);
				buf.append(digit);
			}
		}
	}

	public String toString()
	{
		return buf.toString();
	}

	///////////////////////////////////////////////
	//This is how we'll typically use this class
	///////////////////////////////////////////////
	public static String toString(double d,int prec)
	{
		Format ds=new Format(d,prec);
		return ds.toString();
	}
}

