package curve;

//A couple of routines to print doubles without the 0.888888888 crap
public class PrintableDouble {
  //Return string with number of sig figs
  private double myDouble;
  public PrintableDouble(double d) {
    myDouble=d;
  };

  public String asStringSF(int sf) {
    final double log10overln=0.434294481;
    int fig[]=new int[sf+1];
    int ctr;
    int highestPower;
    double sortOutValue;
    boolean carry;
    String s;

    //Check for zero
    if(myDouble>-0.00001 && myDouble<0.00001) return "0";
    //Get first non-zero digit into integer slot, sign dealt with later
    highestPower=(int)Math.floor(Math.log(Math.abs(myDouble))*log10overln+0.001);
    sortOutValue=(Math.abs(myDouble)*Math.pow(10.0,-highestPower));

    //Get next sf figures
    for(ctr=0;ctr<sf;ctr++) {
      fig[ctr]=(int)(Math.floor(sortOutValue)+0.1);
      sortOutValue-=fig[ctr];
      sortOutValue*=10;
    };

    //round up and carry
    if(sortOutValue>=5) {
      ctr=sf-1;
      do {
        carry=false;
        fig[ctr]++;
        if(fig[ctr]==10) {
          if(ctr==0) {
            for(ctr=sf-1;ctr>0;ctr--) fig[ctr]=fig[ctr-1];
            fig[0]=1;
            highestPower--;
          } else {
            fig[ctr]=0;
            carry=true;
          };
        };
        ctr--;
      } while(carry);
    };

    //Create number string
    if(myDouble<0) s="-"; else s="";
    if(highestPower<0) {
      s+="0.";
      if(highestPower<-1) for(ctr=-1;ctr>highestPower;ctr--) s+=0;
    };
    for(ctr=0;ctr<sf;ctr++) {
      s+=new Integer(fig[ctr]).toString();
      if(highestPower-ctr==0 && ctr+1<sf) s+=".";
    };
    if(highestPower-sf>=0)
      for(ctr=0;ctr<=highestPower-sf;ctr++) s+="0";
    return s;
  };
};