
//------------------------------------------------------------------------------
// SigFig.java:
//		Functions that return a number to the specified number of significant
//      figures or rounded to the specified number of digits.
//------------------------------------------------------------------------------

import java.lang.Math;

public class SigFig
{
	static final int ERROR = -1;

	 // Constructor
	//--------------------------------------------------------------------------
	public SigFig ()
	{
	}

	// Return value with the specified number of significant figures (i)
	// Works for 1e-5 <= value < 1e5, if not in this range, the original
	// value is returned. i must be greater than or equal to 0, if not the
	// original value is returned.
	//--------------------------------------------------------------------------
	public static double sigfig (double value,int i)
	{
	    if(i < 0)
	        return(value);

	    double svalue;
	    double x = Math.pow(10.0,(double) i);
	    double y = 99.0;
	    double nvalue;

	    // Shift significant figures to left of decimal point
	    if(value >= 0.00001 && value < 0.0001)
	        y = x*10000.0;
	    if(value >= 0.0001 && value < 0.001)
	        y = x*1000.0;
	    if(value >= 0.001 && value < 0.01)
	        y = x*100.0;
	    if(value >= 0.01 && value < 0.1)
	        y = x*10.0;
	    if(value >= 0.1 && value < 1.0)
	        y = x;
	    if(value >= 1.0 && value < 10.0)
    	    y = x/10.0;
	    if(value >= 10.0 && value < 100.0)
	        y = x/100.0;
	    if(value >= 100.0 && value < 1000.0)
	        y = x/1000.0;
	    if(value >= 1000.0 && value < 10000.0)
	        y = x/10000.0;
	    if(value >= 10000.0 && value < 100000.0)
	        y = x/100000.0;
	    svalue = value*y;

	    // Remove off unnecessary digits
	    int ii = Math.round((float) svalue);
	    nvalue = (double) ii;

	    // Shift back
	    nvalue = nvalue/y;

	    if(y != 99.0)
	        return(nvalue);
	    else
	        return(value);
	}

	// Return value with the specified number of digits (i) behind the
	// decimal point.  Only works for i >= 0.  Under error conditions
	// the original value is returned.
	//--------------------------------------------------------------------------
	public static double customround (double value,int i)
	{
	    double x = Math.pow(10.0,(double) i);
	    double svalue = value * x;
	    int ii = Math.round((float) svalue);
	    double nvalue = (double) ii;
	    Double z4 = new Double(nvalue);
	    nvalue = nvalue/x;

	    if(i >= 0)
	        return(nvalue);
	    else
	        return(value);
	}

}

