public static void formatDoubleFast(double source,int decimals,int precision,StringBuffer target){
  if (isRoundedToZero(source,decimals,precision)) {
    target.append('0');
    return;
  }
 else   if (Double.isNaN(source) || Double.isInfinite(source)) {
    target.append(Double.toString(source));
    return;
  }
  boolean isPositive=source >= 0.0;
  source=Math.abs(source);
  int scale=(source >= 1.0) ? decimals : precision;
  long intPart=(long)Math.floor(source);
  double tenScale=tenPowDouble(scale);
  double fracUnroundedPart=(source - intPart) * tenScale;
  long fracPart=Math.round(fracUnroundedPart);
  if (fracPart >= tenScale) {
    intPart++;
    fracPart=Math.round(fracPart - tenScale);
  }
  if (fracPart != 0L) {
    while (fracPart % 10L == 0L) {
      fracPart=fracPart / 10L;
      scale--;
    }
  }
  if (intPart != 0L || fracPart != 0L) {
    if (!isPositive) {
      target.append('-');
    }
    target.append(intPart);
    if (fracPart != 0L) {
      target.append('.');
      while (scale > 0 && fracPart < tenPowDouble(--scale)) {
        target.append('0');
      }
      target.append(fracPart);
    }
  }
 else {
    target.append('0');
  }
}

public static void formatDoubleFast ( double source , int decimals , int precision , StringBuffer target ) { if ( isRoundedToZero ( source , decimals , precision ) ) { target . append ( '0' ) ; return ; } else if ( Double . isNaN ( source ) || Double . isInfinite ( source ) ) { target . append ( Double . toString ( source ) ) ; return ; } boolean isPositive = source >= 0.0 ; source = Math . abs ( source ) ; int scale = ( source >= 1.0 ) ? decimals : precision ; long intPart = ( long ) Math . floor ( source ) ; double tenScale = tenPowDouble ( scale ) ; double fracUnroundedPart = ( source - intPart ) * tenScale ; long fracPart = Math . round ( fracUnroundedPart ) ; if ( fracPart >= tenScale ) { intPart ++ ; fracPart = Math . round ( fracPart - tenScale ) ; } if ( fracPart != 0L ) { while ( fracPart % 10L == 0L ) { fracPart = fracPart / 10L ; scale -- ; } } if ( intPart != 0L || fracPart != 0L ) { if ( ! isPositive ) { target . append ( '-' ) ; } target . append ( intPart ) ; if ( fracPart != 0L ) { target . append ( '.' ) ; while ( scale > 0 && fracPart < tenPowDouble ( -- scale ) ) { target . append ( '0' ) ; } target . append ( fracPart ) ; } } else { target . append ( '0' ) ; } }
rounds the given source value at the given precision and writes the rounded value into the given target < p > this method internally uses double precision computation and rounding , so the result may not be accurate ( see formatdouble method for conditions ) .
