1 /*
   2  * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.nashorn.internal.runtime;
  27 
  28 import java.math.BigInteger;
  29 
  30 /**
  31  * JavaScript number to string conversion, refinement of sun.misc.FloatingDecimal.
  32  */
  33 public final class NumberToString {
  34     /** Is not a number flag */
  35     private final boolean isNaN;
  36 
  37     /** Is a negative number flag. */
  38     private boolean isNegative;
  39 
  40     /** Decimal exponent value (for E notation.) */
  41     private int decimalExponent;
  42 
  43     /** Actual digits. */
  44     private char digits[];
  45 
  46     /** Number of digits to use. (nDigits <= digits.length). */
  47     private int nDigits;
  48 
  49     /*
  50      * IEEE-754 constants.
  51      */
  52 
  53     //private static final long   signMask           = 0x8000000000000000L;
  54     private static final int    expMask            = 0x7FF;
  55     private static final long   fractMask          = 0x000F_FFFF_FFFF_FFFFL;
  56     private static final int    expShift           = 52;
  57     private static final int    expBias            = 1_023;
  58     private static final long   fractHOB           = (1L << expShift);
  59     private static final long   expOne             = ((long)expBias) << expShift;
  60     private static final int    maxSmallBinExp     = 62;
  61     private static final int    minSmallBinExp     = -(63 / 3);
  62 
  63     /** Powers of 5 fitting a long. */
  64     private static final long powersOf5[] = {
  65         1L,
  66         5L,
  67         5L * 5,
  68         5L * 5 * 5,
  69         5L * 5 * 5 * 5,
  70         5L * 5 * 5 * 5 * 5,
  71         5L * 5 * 5 * 5 * 5 * 5,
  72         5L * 5 * 5 * 5 * 5 * 5 * 5,
  73         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  74         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  75         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  76         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  77         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  78         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  79         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  80         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  81         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  82         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  83         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  84         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  85         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  86         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  87         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  88         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  89         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  90         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
  91         5L * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5
  92     };
  93 
  94     // Approximately ceil(log2(longPowers5[i])).
  95     private static final int nBitsPowerOf5[] = {
  96         0,
  97         3,
  98         5,
  99         7,
 100         10,
 101         12,
 102         14,
 103         17,
 104         19,
 105         21,
 106         24,
 107         26,
 108         28,
 109         31,
 110         33,
 111         35,
 112         38,
 113         40,
 114         42,
 115         45,
 116         47,
 117         49,
 118         52,
 119         54,
 120         56,
 121         59,
 122         61
 123     };
 124 
 125     /** Digits used for infinity result. */
 126     private static final char infinityDigits[]   = { 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y' };
 127 
 128     /** Digits used for NaN result. */
 129     private static final char nanDigits[]        = { 'N', 'a', 'N' };
 130 
 131     /** Zeros used to pad result. */
 132     private static final char zeroes[]           = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' };
 133 
 134 
 135     /**
 136      * Convert a number into a JavaScript string.
 137      * @param value Double to convert.
 138      * @return JavaScript formated number.
 139      */
 140     public static String stringFor(final double value) {
 141         return new NumberToString(value).toString();
 142     }
 143 
 144     /*
 145      * Constructor.
 146      */
 147 
 148     private NumberToString(final double value) {
 149         // Double as bits.
 150         long bits = Double.doubleToLongBits(value);
 151 
 152         // Get upper word.
 153         final int upper = (int)(bits >> 32);
 154 
 155         // Detect sign.
 156         isNegative = upper < 0;
 157 
 158         // Extract exponent.
 159         int exponent = (upper >> (expShift - 32)) & expMask;
 160 
 161         // Clear sign and exponent.
 162         bits &= fractMask;
 163 
 164         // Detect NaN.
 165         if (exponent == expMask) {
 166             isNaN = true;
 167 
 168             // Detect Infinity.
 169             if (bits == 0L) {
 170                 digits =  infinityDigits;
 171             } else {
 172                 digits = nanDigits;
 173                 isNegative = false;
 174             }
 175 
 176             nDigits = digits.length;
 177 
 178             return;
 179         }
 180 
 181         // We have a working double.
 182         isNaN = false;
 183 
 184         int nSignificantBits;
 185 
 186         // Detect denormalized value.
 187         if (exponent == 0) {
 188             // Detect zero value.
 189             if (bits == 0L) {
 190                 decimalExponent = 0;
 191                 digits = zeroes;
 192                 nDigits = 1;
 193 
 194                 return;
 195             }
 196 
 197             // Normalize value, using highest significant bit as HOB.
 198             while ((bits & fractHOB) == 0L) {
 199                 bits <<= 1;
 200                 exponent -= 1;
 201             }
 202 
 203             // Compute number of significant bits.
 204             nSignificantBits = expShift + exponent +1;
 205             // Bias exponent by HOB.
 206             exponent += 1;
 207         } else {
 208             // Add implicit HOB.
 209             bits |= fractHOB;
 210             // Compute number of significant bits.
 211             nSignificantBits = expShift + 1;
 212         }
 213 
 214         // Unbias exponent (represents bit shift).
 215         exponent -= expBias;
 216 
 217         // Determine the number of significant bits in the fraction.
 218         final int nFractBits = countSignificantBits(bits);
 219 
 220         // Number of bits to the right of the decimal.
 221         final int nTinyBits = Math.max(0, nFractBits - exponent - 1);
 222 
 223         // Computed decimal exponent.
 224         int decExponent;
 225 
 226         if (exponent <= maxSmallBinExp && exponent >= minSmallBinExp) {
 227             // Look more closely at the number to decide if,
 228             // with scaling by 10^nTinyBits, the result will fit in
 229             // a long.
 230             if (nTinyBits < powersOf5.length && (nFractBits + nBitsPowerOf5[nTinyBits]) < 64) {
 231                 /*
 232                  * We can do this:
 233                  * take the fraction bits, which are normalized.
 234                  * (a) nTinyBits == 0: Shift left or right appropriately
 235                  *     to align the binary point at the extreme right, i.e.
 236                  *     where a long int point is expected to be. The integer
 237                  *     result is easily converted to a string.
 238                  * (b) nTinyBits > 0: Shift right by expShift - nFractBits,
 239                  *     which effectively converts to long and scales by
 240                  *     2^nTinyBits. Then multiply by 5^nTinyBits to
 241                  *     complete the scaling. We know this won't overflow
 242                  *     because we just counted the number of bits necessary
 243                  *     in the result. The integer you get from this can
 244                  *     then be converted to a string pretty easily.
 245                  */
 246 
 247                 if (nTinyBits == 0) {
 248                     long halfULP;
 249 
 250                     if (exponent > nSignificantBits) {
 251                         halfULP = 1L << (exponent - nSignificantBits - 1);
 252                     } else {
 253                         halfULP = 0L;
 254                     }
 255 
 256                     if (exponent >= expShift) {
 257                         bits <<= exponent - expShift;
 258                     } else {
 259                         bits >>>= expShift - exponent;
 260                     }
 261 
 262                     // Discard non-significant low-order bits, while rounding,
 263                     // up to insignificant value.
 264                     int i;
 265                     for (i = 0; halfULP >= 10L; i++) {
 266                         halfULP /= 10L;
 267                     }
 268 
 269                     /**
 270                      * This is the easy subcase --
 271                      * all the significant bits, after scaling, are held in bits.
 272                      * isNegative and decExponent tell us what processing and scaling
 273                      * has already been done. Exceptional cases have already been
 274                      * stripped out.
 275                      * In particular:
 276                      *      bits is a finite number (not Infinite, nor NaN)
 277                      *      bits > 0L (not zero, nor negative).
 278                      *
 279                      * The only reason that we develop the digits here, rather than
 280                      * calling on Long.toString() is that we can do it a little faster,
 281                      * and besides want to treat trailing 0s specially. If Long.toString
 282                      * changes, we should re-evaluate this strategy!
 283                      */
 284 
 285                     int decExp = 0;
 286 
 287                     if (i != 0) {
 288                          // 10^i == 5^i * 2^i
 289                         final long powerOf10 = powersOf5[i] << i;
 290                         final long residue = bits % powerOf10;
 291                         bits /= powerOf10;
 292                         decExp += i;
 293 
 294                         if (residue >= (powerOf10 >> 1)) {
 295                             // Round up based on the low-order bits we're discarding.
 296                             bits++;
 297                         }
 298                     }
 299 
 300                     int ndigits = 20;
 301                     final char[] digits0 = new char[26];
 302                     int digitno = ndigits - 1;
 303                     int c = (int)(bits % 10L);
 304                     bits /= 10L;
 305 
 306                     while (c == 0) {
 307                         decExp++;
 308                         c = (int)(bits % 10L);
 309                         bits /= 10L;
 310                     }
 311 
 312                     while (bits != 0L) {
 313                         digits0[digitno--] = (char)(c + '0');
 314                         decExp++;
 315                         c = (int)(bits % 10L);
 316                         bits /= 10;
 317                     }
 318 
 319                     digits0[digitno] = (char)(c + '0');
 320 
 321                     ndigits -= digitno;
 322                     final char[] result = new char[ndigits];
 323                     System.arraycopy(digits0, digitno, result, 0, ndigits);
 324 
 325                     this.digits          = result;
 326                     this.decimalExponent = decExp + 1;
 327                     this.nDigits         = ndigits;
 328 
 329                     return;
 330                 }
 331             }
 332         }
 333 
 334         /*
 335          * This is the hard case. We are going to compute large positive
 336          * integers B and S and integer decExp, s.t.
 337          *      d = (B / S) * 10^decExp
 338          *      1 <= B / S < 10
 339          * Obvious choices are:
 340          *      decExp = floor(log10(d))
 341          *      B      = d * 2^nTinyBits * 10^max(0, -decExp)
 342          *      S      = 10^max(0, decExp) * 2^nTinyBits
 343          * (noting that nTinyBits has already been forced to non-negative)
 344          * I am also going to compute a large positive integer
 345          *      M      = (1/2^nSignificantBits) * 2^nTinyBits * 10^max(0, -decExp)
 346          * i.e. M is (1/2) of the ULP of d, scaled like B.
 347          * When we iterate through dividing B/S and picking off the
 348          * quotient bits, we will know when to stop when the remainder
 349          * is <= M.
 350          *
 351          * We keep track of powers of 2 and powers of 5.
 352          */
 353 
 354         /*
 355          * Estimate decimal exponent. (If it is small-ish,
 356          * we could double-check.)
 357          *
 358          * First, scale the mantissa bits such that 1 <= d2 < 2.
 359          * We are then going to estimate
 360          *          log10(d2) ~=~  (d2-1.5)/1.5 + log(1.5)
 361          * and so we can estimate
 362          *      log10(d) ~=~ log10(d2) + binExp * log10(2)
 363          * take the floor and call it decExp.
 364          */
 365         final double d2 = Double.longBitsToDouble(expOne | (bits & ~fractHOB));
 366         decExponent = (int)Math.floor((d2 - 1.5D) * 0.289529654D + 0.176091259D + exponent * 0.301029995663981D);
 367 
 368         // Powers of 2 and powers of 5, respectively, in B.
 369         final int B5 = Math.max(0, -decExponent);
 370         int B2 = B5 + nTinyBits + exponent;
 371 
 372         // Powers of 2 and powers of 5, respectively, in S.
 373         final int S5 = Math.max(0, decExponent);
 374         int S2 = S5 + nTinyBits;
 375 
 376         // Powers of 2 and powers of 5, respectively, in M.
 377         final int M5 = B5;
 378         int M2 = B2 - nSignificantBits;
 379 
 380         /*
 381          * The long integer fractBits contains the (nFractBits) interesting
 382          * bits from the mantissa of d (hidden 1 added if necessary) followed
 383          * by (expShift + 1 - nFractBits) zeros. In the interest of compactness,
 384          * I will shift out those zeros before turning fractBits into a
 385          * BigInteger. The resulting whole number will be
 386          *      d * 2^(nFractBits - 1 - binExp).
 387          */
 388 
 389         bits >>>= expShift + 1 - nFractBits;
 390         B2 -= nFractBits - 1;
 391         final int common2factor = Math.min(B2, S2);
 392         B2 -= common2factor;
 393         S2 -= common2factor;
 394         M2 -= common2factor;
 395 
 396         /*
 397          * HACK!!For exact powers of two, the next smallest number
 398          * is only half as far away as we think (because the meaning of
 399          * ULP changes at power-of-two bounds) for this reason, we
 400          * hack M2. Hope this works.
 401          */
 402         if (nFractBits == 1) {
 403             M2 -= 1;
 404         }
 405 
 406         if (M2 < 0) {
 407             // Oops.  Since we cannot scale M down far enough,
 408             // we must scale the other values up.
 409             B2 -= M2;
 410             S2 -= M2;
 411             M2 =  0;
 412         }
 413 
 414         /*
 415          * Construct, Scale, iterate.
 416          * Some day, we'll write a stopping test that takes
 417          * account of the asymmetry of the spacing of floating-point
 418          * numbers below perfect powers of 2
 419          * 26 Sept 96 is not that day.
 420          * So we use a symmetric test.
 421          */
 422 
 423         final char digits0[] = this.digits = new char[32];
 424         int  ndigit;
 425         boolean low, high;
 426         long lowDigitDifference;
 427         int  q;
 428 
 429         /*
 430          * Detect the special cases where all the numbers we are about
 431          * to compute will fit in int or long integers.
 432          * In these cases, we will avoid doing BigInteger arithmetic.
 433          * We use the same algorithms, except that we "normalize"
 434          * our FDBigInts before iterating. This is to make division easier,
 435          * as it makes our fist guess (quotient of high-order words)
 436          * more accurate!
 437          */
 438 
 439         // Binary digits needed to represent B, approx.
 440         final int Bbits = nFractBits + B2 + ((B5 < nBitsPowerOf5.length) ? nBitsPowerOf5[B5] : (B5*3));
 441         // Binary digits needed to represent 10*S, approx.
 442         final int tenSbits = S2 + 1 + (((S5 + 1) < nBitsPowerOf5.length) ? nBitsPowerOf5[(S5 + 1)] : ((S5 + 1) * 3));
 443 
 444         if (Bbits < 64 && tenSbits < 64) {
 445             long b = (bits * powersOf5[B5]) << B2;
 446             final long s = powersOf5[S5] << S2;
 447             long m = powersOf5[M5] << M2;
 448             final long tens = s * 10L;
 449 
 450             /*
 451              * Unroll the first iteration. If our decExp estimate
 452              * was too high, our first quotient will be zero. In this
 453              * case, we discard it and decrement decExp.
 454              */
 455 
 456             ndigit = 0;
 457             q = (int)(b / s);
 458             b = 10L * (b % s);
 459             m *= 10L;
 460             low  = b <  m;
 461             high = (b + m) > tens;
 462 
 463             if (q == 0 && !high) {
 464                 // Ignore leading zero.
 465                 decExponent--;
 466             } else {
 467                 digits0[ndigit++] = (char)('0' + q);
 468             }
 469 
 470             if (decExponent < -3 || decExponent >= 8) {
 471                 high = low = false;
 472             }
 473 
 474             while (!low && !high) {
 475                 q = (int)(b / s);
 476                 b = 10 * (b % s);
 477                 m *= 10;
 478 
 479                 if (m > 0L) {
 480                     low  = b < m;
 481                     high = (b + m) > tens;
 482                 } else {
 483                     low = true;
 484                     high = true;
 485                 }
 486 
 487                 if (low && q == 0) {
 488                     break;
 489                 }
 490                 digits0[ndigit++] = (char)('0' + q);
 491             }
 492 
 493             lowDigitDifference = (b << 1) - tens;
 494         } else {
 495             /*
 496              * We must do BigInteger arithmetic.
 497              * First, construct our BigInteger initial values.
 498              */
 499 
 500             BigInteger Bval = multiplyPowerOf5And2(BigInteger.valueOf(bits), B5, B2);
 501             BigInteger Sval = constructPowerOf5And2(S5, S2);
 502             BigInteger Mval = constructPowerOf5And2(M5, M2);
 503 
 504 
 505             // Normalize so that BigInteger division works better.
 506             final int shiftBias = Long.numberOfLeadingZeros(bits) - 4;
 507             Bval = Bval.shiftLeft(shiftBias);
 508             Mval = Mval.shiftLeft(shiftBias);
 509             Sval = Sval.shiftLeft(shiftBias);
 510             final BigInteger tenSval = Sval.multiply(BigInteger.TEN);
 511 
 512             /*
 513              * Unroll the first iteration. If our decExp estimate
 514              * was too high, our first quotient will be zero. In this
 515              * case, we discard it and decrement decExp.
 516              */
 517 
 518             ndigit = 0;
 519 
 520             BigInteger[] quoRem = Bval.divideAndRemainder(Sval);
 521             q    = quoRem[0].intValue();
 522             Bval = quoRem[1].multiply(BigInteger.TEN);
 523             Mval = Mval.multiply(BigInteger.TEN);
 524             low  = (Bval.compareTo(Mval) < 0);
 525             high = (Bval.add(Mval).compareTo(tenSval) > 0);
 526 
 527             if (q == 0 && !high) {
 528                 // Ignore leading zero.
 529                 decExponent--;
 530             } else {
 531                 digits0[ndigit++] = (char)('0' + q);
 532             }
 533 
 534             if (decExponent < -3 || decExponent >= 8) {
 535                 high = low = false;
 536             }
 537 
 538             while(!low && !high) {
 539                 quoRem = Bval.divideAndRemainder(Sval);
 540                 q = quoRem[0].intValue();
 541                 Bval = quoRem[1].multiply(BigInteger.TEN);
 542                 Mval = Mval.multiply(BigInteger.TEN);
 543                 low  = (Bval.compareTo(Mval) < 0);
 544                 high = (Bval.add(Mval).compareTo(tenSval) > 0);
 545 
 546                 if (low && q == 0) {
 547                     break;
 548                 }
 549                 digits0[ndigit++] = (char)('0' + q);
 550             }
 551 
 552             if (high && low) {
 553                 Bval = Bval.shiftLeft(1);
 554                 lowDigitDifference = Bval.compareTo(tenSval);
 555             } else {
 556                 lowDigitDifference = 0L;
 557             }
 558         }
 559 
 560         this.decimalExponent = decExponent + 1;
 561         this.digits          = digits0;
 562         this.nDigits         = ndigit;
 563 
 564         /*
 565          * Last digit gets rounded based on stopping condition.
 566          */
 567 
 568         if (high) {
 569             if (low) {
 570                 if (lowDigitDifference == 0L) {
 571                     // it's a tie!
 572                     // choose based on which digits we like.
 573                     if ((digits0[nDigits - 1] & 1) != 0) {
 574                         roundup();
 575                     }
 576                 } else if (lowDigitDifference > 0) {
 577                     roundup();
 578                 }
 579             } else {
 580                 roundup();
 581             }
 582         }
 583     }
 584 
 585     /**
 586      * Count number of significant bits.
 587      * @param bits Double's fraction.
 588      * @return Number of significant bits.
 589      */
 590     private static int countSignificantBits(final long bits) {
 591         if (bits != 0) {
 592             return 64 - Long.numberOfLeadingZeros(bits) - Long.numberOfTrailingZeros(bits);
 593         }
 594 
 595         return 0;
 596     }
 597 
 598     /*
 599      * Cache big powers of 5 handy for future reference.
 600      */
 601     private static BigInteger powerOf5Cache[];
 602 
 603     /**
 604      * Determine the largest power of 5 needed (as BigInteger.)
 605      * @param power Power of 5.
 606      * @return BigInteger of power of 5.
 607      */
 608     private static BigInteger bigPowerOf5(final int power) {
 609         if (powerOf5Cache == null) {
 610             powerOf5Cache = new BigInteger[power + 1];
 611         } else if (powerOf5Cache.length <= power) {
 612             final BigInteger t[] = new BigInteger[ power+1 ];
 613             System.arraycopy(powerOf5Cache, 0, t, 0, powerOf5Cache.length);
 614             powerOf5Cache = t;
 615         }
 616 
 617         if (powerOf5Cache[power] != null) {
 618             return powerOf5Cache[power];
 619         } else if (power < powersOf5.length) {
 620             return powerOf5Cache[power] = BigInteger.valueOf(powersOf5[power]);
 621         } else {
 622             // Construct the value recursively.
 623             // in order to compute 5^p,
 624             // compute its square root, 5^(p/2) and square.
 625             // or, let q = p / 2, r = p -q, then
 626             // 5^p = 5^(q+r) = 5^q * 5^r
 627             final int q = power >> 1;
 628             final int r = power - q;
 629             BigInteger bigQ = powerOf5Cache[q];
 630 
 631             if (bigQ == null) {
 632                 bigQ = bigPowerOf5(q);
 633             }
 634 
 635             if (r < powersOf5.length) {
 636                 return (powerOf5Cache[power] = bigQ.multiply(BigInteger.valueOf(powersOf5[r])));
 637             }
 638             BigInteger bigR = powerOf5Cache[ r ];
 639 
 640             if (bigR == null) {
 641                 bigR = bigPowerOf5(r);
 642             }
 643 
 644             return (powerOf5Cache[power] = bigQ.multiply(bigR));
 645         }
 646     }
 647 
 648     /**
 649      * Multiply BigInteger by powers of 5 and 2 (i.e., 10)
 650      * @param value Value to multiply.
 651      * @param p5    Power of 5.
 652      * @param p2    Power of 2.
 653      * @return Result.
 654      */
 655     private static BigInteger multiplyPowerOf5And2(final BigInteger value, final int p5, final int p2) {
 656         BigInteger returnValue = value;
 657 
 658         if (p5 != 0) {
 659             returnValue = returnValue.multiply(bigPowerOf5(p5));
 660         }
 661 
 662         if (p2 != 0) {
 663             returnValue = returnValue.shiftLeft(p2);
 664         }
 665 
 666         return returnValue;
 667     }
 668 
 669     /**
 670      * Construct a BigInteger power of 5 and 2 (i.e., 10)
 671      * @param p5    Power of 5.
 672      * @param p2    Power of 2.
 673      * @return Result.
 674      */
 675     private static BigInteger constructPowerOf5And2(final int p5, final int p2) {
 676         BigInteger v = bigPowerOf5(p5);
 677 
 678         if (p2 != 0) {
 679             v = v.shiftLeft(p2);
 680         }
 681 
 682         return v;
 683     }
 684 
 685     /**
 686      * Round up last digit by adding one to the least significant digit.
 687      * In the unlikely event there is a carry out, deal with it.
 688      * assert that this will only happen where there
 689      * is only one digit, e.g. (float)1e-44 seems to do it.
 690      */
 691     private void roundup() {
 692         int i;
 693         int q = digits[ i = (nDigits-1)];
 694 
 695         while (q == '9' && i > 0) {
 696             if (decimalExponent < 0) {
 697                 nDigits--;
 698             } else {
 699                 digits[i] = '0';
 700             }
 701 
 702             q = digits[--i];
 703         }
 704 
 705         if (q == '9') {
 706             // Carryout! High-order 1, rest 0s, larger exp.
 707             decimalExponent += 1;
 708             digits[0] = '1';
 709 
 710             return;
 711         }
 712 
 713         digits[i] = (char)(q + 1);
 714     }
 715 
 716     /**
 717      * Format final number string.
 718      * @return Formatted string.
 719      */
 720     @Override
 721     public String toString() {
 722         final StringBuilder sb = new StringBuilder(32);
 723 
 724         if (isNegative) {
 725             sb.append('-');
 726         }
 727 
 728         if (isNaN) {
 729             sb.append(digits, 0, nDigits);
 730         } else {
 731             if (decimalExponent > 0 && decimalExponent <= 21) {
 732                 final int charLength = Math.min(nDigits, decimalExponent);
 733                 sb.append(digits, 0, charLength);
 734 
 735                 if (charLength < decimalExponent) {
 736                     sb.append(zeroes, 0, decimalExponent - charLength);
 737                 } else if (charLength < nDigits) {
 738                     sb.append('.');
 739                     sb.append(digits, charLength, nDigits - charLength);
 740                 }
 741             } else if (decimalExponent <=0 && decimalExponent > -6) {
 742                 sb.append('0');
 743                 sb.append('.');
 744 
 745                 if (decimalExponent != 0) {
 746                     sb.append(zeroes, 0, -decimalExponent);
 747                 }
 748 
 749                 sb.append(digits, 0, nDigits);
 750             } else {
 751                 sb.append(digits[0]);
 752 
 753                 if (nDigits > 1) {
 754                     sb.append('.');
 755                     sb.append(digits, 1, nDigits - 1);
 756                 }
 757 
 758                 sb.append('e');
 759                 final int exponent;
 760                 int e;
 761 
 762                 if (decimalExponent <= 0) {
 763                     sb.append('-');
 764                     exponent = e = -decimalExponent + 1;
 765                 } else {
 766                     sb.append('+');
 767                     exponent = e = decimalExponent - 1;
 768                 }
 769 
 770                 if (exponent > 99) {
 771                     sb.append((char)(e / 100 + '0'));
 772                     e %= 100;
 773                 }
 774 
 775                 if (exponent > 9) {
 776                     sb.append((char)(e / 10 + '0'));
 777                     e %= 10;
 778                 }
 779 
 780                 sb.append((char)(e + '0'));
 781             }
 782         }
 783 
 784         return sb.toString();
 785     }
 786 }