github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/internal/jsre/deps/bignumber.js (about)

     1  /*! bignumber.js v2.0.7 https://github.com/MikeMcl/bignumber.js/LICENCE */
     2  
     3  ;(function (global) {
     4      'use strict';
     5  
     6      /*
     7        bignumber.js v2.0.7
     8        A JavaScript library for arbitrary-precision arithmetic.
     9        https://github.com/MikeMcl/bignumber.js
    10        Copyright (c) 2015 Michael Mclaughlin <M8ch88l@gmail.com>
    11        MIT Expat Licence
    12      */
    13  
    14  
    15      var BigNumber, crypto, parseNumeric,
    16          isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
    17          mathceil = Math.ceil,
    18          mathfloor = Math.floor,
    19          notBool = ' not a boolean or binary digit',
    20          roundingMode = 'rounding mode',
    21          tooManyDigits = 'number type has more than 15 significant digits',
    22          ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
    23          BASE = 1e14,
    24          LOG_BASE = 14,
    25          MAX_SAFE_INTEGER = 0x1fffffffffffff,         // 2^53 - 1
    26          // MAX_INT32 = 0x7fffffff,                   // 2^31 - 1
    27          POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
    28          SQRT_BASE = 1e7,
    29  
    30          /*
    31           * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
    32           * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
    33           * exception is thrown (if ERRORS is true).
    34           */
    35          MAX = 1E9;                                   // 0 to MAX_INT32
    36  
    37  
    38      /*
    39       * Create and return a BigNumber constructor.
    40       */
    41      function another(configObj) {
    42          var div,
    43  
    44              // id tracks the caller function, so its name can be included in error messages.
    45              id = 0,
    46              P = BigNumber.prototype,
    47              ONE = new BigNumber(1),
    48  
    49  
    50              /********************************* EDITABLE DEFAULTS **********************************/
    51  
    52  
    53              /*
    54               * The default values below must be integers within the inclusive ranges stated.
    55               * The values can also be changed at run-time using BigNumber.config.
    56               */
    57  
    58              // The maximum number of decimal places for operations involving division.
    59              DECIMAL_PLACES = 20,                     // 0 to MAX
    60  
    61              /*
    62               * The rounding mode used when rounding to the above decimal places, and when using
    63               * toExponential, toFixed, toFormat and toPrecision, and round (default value).
    64               * UP         0 Away from zero.
    65               * DOWN       1 Towards zero.
    66               * CEIL       2 Towards +Infinity.
    67               * FLOOR      3 Towards -Infinity.
    68               * HALF_UP    4 Towards nearest neighbour. If equidistant, up.
    69               * HALF_DOWN  5 Towards nearest neighbour. If equidistant, down.
    70               * HALF_EVEN  6 Towards nearest neighbour. If equidistant, towards even neighbour.
    71               * HALF_CEIL  7 Towards nearest neighbour. If equidistant, towards +Infinity.
    72               * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
    73               */
    74              ROUNDING_MODE = 4,                       // 0 to 8
    75  
    76              // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
    77  
    78              // The exponent value at and beneath which toString returns exponential notation.
    79              // Number type: -7
    80              TO_EXP_NEG = -7,                         // 0 to -MAX
    81  
    82              // The exponent value at and above which toString returns exponential notation.
    83              // Number type: 21
    84              TO_EXP_POS = 21,                         // 0 to MAX
    85  
    86              // RANGE : [MIN_EXP, MAX_EXP]
    87  
    88              // The minimum exponent value, beneath which underflow to zero occurs.
    89              // Number type: -324  (5e-324)
    90              MIN_EXP = -1e7,                          // -1 to -MAX
    91  
    92              // The maximum exponent value, above which overflow to Infinity occurs.
    93              // Number type:  308  (1.7976931348623157e+308)
    94              // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
    95              MAX_EXP = 1e7,                           // 1 to MAX
    96  
    97              // Whether BigNumber Errors are ever thrown.
    98              ERRORS = true,                           // true or false
    99  
   100              // Change to intValidatorNoErrors if ERRORS is false.
   101              isValidInt = intValidatorWithErrors,     // intValidatorWithErrors/intValidatorNoErrors
   102  
   103              // Whether to use cryptographically-secure random number generation, if available.
   104              CRYPTO = false,                          // true or false
   105  
   106              /*
   107               * The modulo mode used when calculating the modulus: a mod n.
   108               * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
   109               * The remainder (r) is calculated as: r = a - n * q.
   110               *
   111               * UP        0 The remainder is positive if the dividend is negative, else is negative.
   112               * DOWN      1 The remainder has the same sign as the dividend.
   113               *             This modulo mode is commonly known as 'truncated division' and is
   114               *             equivalent to (a % n) in JavaScript.
   115               * FLOOR     3 The remainder has the same sign as the divisor (Python %).
   116               * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
   117               * EUCLID    9 Euclidian division. q = sign(n) * floor(a / abs(n)).
   118               *             The remainder is always positive.
   119               *
   120               * The truncated division, floored division, Euclidian division and IEEE 754 remainder
   121               * modes are commonly used for the modulus operation.
   122               * Although the other rounding modes can also be used, they may not give useful results.
   123               */
   124              MODULO_MODE = 1,                         // 0 to 9
   125  
   126              // The maximum number of significant digits of the result of the toPower operation.
   127              // If POW_PRECISION is 0, there will be unlimited significant digits.
   128              POW_PRECISION = 100,                     // 0 to MAX
   129  
   130              // The format specification used by the BigNumber.prototype.toFormat method.
   131              FORMAT = {
   132                  decimalSeparator: '.',
   133                  groupSeparator: ',',
   134                  groupSize: 3,
   135                  secondaryGroupSize: 0,
   136                  fractionGroupSeparator: '\xA0',      // non-breaking space
   137                  fractionGroupSize: 0
   138              };
   139  
   140  
   141          /******************************************************************************************/
   142  
   143  
   144          // CONSTRUCTOR
   145  
   146  
   147          /*
   148           * The BigNumber constructor and exported function.
   149           * Create and return a new instance of a BigNumber object.
   150           *
   151           * n {number|string|BigNumber} A numeric value.
   152           * [b] {number} The base of n. Integer, 2 to 64 inclusive.
   153           */
   154          function BigNumber( n, b ) {
   155              var c, e, i, num, len, str,
   156                  x = this;
   157  
   158              // Enable constructor usage without new.
   159              if ( !( x instanceof BigNumber ) ) {
   160  
   161                  // 'BigNumber() constructor call without new: {n}'
   162                  if (ERRORS) raise( 26, 'constructor call without new', n );
   163                  return new BigNumber( n, b );
   164              }
   165  
   166              // 'new BigNumber() base not an integer: {b}'
   167              // 'new BigNumber() base out of range: {b}'
   168              if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
   169  
   170                  // Duplicate.
   171                  if ( n instanceof BigNumber ) {
   172                      x.s = n.s;
   173                      x.e = n.e;
   174                      x.c = ( n = n.c ) ? n.slice() : n;
   175                      id = 0;
   176                      return;
   177                  }
   178  
   179                  if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
   180                      x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
   181  
   182                      // Fast path for integers.
   183                      if ( n === ~~n ) {
   184                          for ( e = 0, i = n; i >= 10; i /= 10, e++ );
   185                          x.e = e;
   186                          x.c = [n];
   187                          id = 0;
   188                          return;
   189                      }
   190  
   191                      str = n + '';
   192                  } else {
   193                      if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
   194                      x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
   195                  }
   196              } else {
   197                  b = b | 0;
   198                  str = n + '';
   199  
   200                  // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
   201                  // Allow exponential notation to be used with base 10 argument.
   202                  if ( b == 10 ) {
   203                      x = new BigNumber( n instanceof BigNumber ? n : str );
   204                      return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
   205                  }
   206  
   207                  // Avoid potential interpretation of Infinity and NaN as base 44+ values.
   208                  // Any number in exponential form will fail due to the [Ee][+-].
   209                  if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
   210                    !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
   211                      '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
   212                      return parseNumeric( x, str, num, b );
   213                  }
   214  
   215                  if (num) {
   216                      x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
   217  
   218                      if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
   219  
   220                          // 'new BigNumber() number type has more than 15 significant digits: {n}'
   221                          raise( id, tooManyDigits, n );
   222                      }
   223  
   224                      // Prevent later check for length on converted number.
   225                      num = false;
   226                  } else {
   227                      x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
   228                  }
   229  
   230                  str = convertBase( str, 10, b, x.s );
   231              }
   232  
   233              // Decimal point?
   234              if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
   235  
   236              // Exponential form?
   237              if ( ( i = str.search( /e/i ) ) > 0 ) {
   238  
   239                  // Determine exponent.
   240                  if ( e < 0 ) e = i;
   241                  e += +str.slice( i + 1 );
   242                  str = str.substring( 0, i );
   243              } else if ( e < 0 ) {
   244  
   245                  // Integer.
   246                  e = str.length;
   247              }
   248  
   249              // Determine leading zeros.
   250              for ( i = 0; str.charCodeAt(i) === 48; i++ );
   251  
   252              // Determine trailing zeros.
   253              for ( len = str.length; str.charCodeAt(--len) === 48; );
   254              str = str.slice( i, len + 1 );
   255  
   256              if (str) {
   257                  len = str.length;
   258  
   259                  // Disallow numbers with over 15 significant digits if number type.
   260                  // 'new BigNumber() number type has more than 15 significant digits: {n}'
   261                  if ( num && ERRORS && len > 15 ) raise( id, tooManyDigits, x.s * n );
   262  
   263                  e = e - i - 1;
   264  
   265                   // Overflow?
   266                  if ( e > MAX_EXP ) {
   267  
   268                      // Infinity.
   269                      x.c = x.e = null;
   270  
   271                  // Underflow?
   272                  } else if ( e < MIN_EXP ) {
   273  
   274                      // Zero.
   275                      x.c = [ x.e = 0 ];
   276                  } else {
   277                      x.e = e;
   278                      x.c = [];
   279  
   280                      // Transform base
   281  
   282                      // e is the base 10 exponent.
   283                      // i is where to slice str to get the first element of the coefficient array.
   284                      i = ( e + 1 ) % LOG_BASE;
   285                      if ( e < 0 ) i += LOG_BASE;
   286  
   287                      if ( i < len ) {
   288                          if (i) x.c.push( +str.slice( 0, i ) );
   289  
   290                          for ( len -= LOG_BASE; i < len; ) {
   291                              x.c.push( +str.slice( i, i += LOG_BASE ) );
   292                          }
   293  
   294                          str = str.slice(i);
   295                          i = LOG_BASE - str.length;
   296                      } else {
   297                          i -= len;
   298                      }
   299  
   300                      for ( ; i--; str += '0' );
   301                      x.c.push( +str );
   302                  }
   303              } else {
   304  
   305                  // Zero.
   306                  x.c = [ x.e = 0 ];
   307              }
   308  
   309              id = 0;
   310          }
   311  
   312  
   313          // CONSTRUCTOR PROPERTIES
   314  
   315  
   316          BigNumber.another = another;
   317  
   318          BigNumber.ROUND_UP = 0;
   319          BigNumber.ROUND_DOWN = 1;
   320          BigNumber.ROUND_CEIL = 2;
   321          BigNumber.ROUND_FLOOR = 3;
   322          BigNumber.ROUND_HALF_UP = 4;
   323          BigNumber.ROUND_HALF_DOWN = 5;
   324          BigNumber.ROUND_HALF_EVEN = 6;
   325          BigNumber.ROUND_HALF_CEIL = 7;
   326          BigNumber.ROUND_HALF_FLOOR = 8;
   327          BigNumber.EUCLID = 9;
   328  
   329  
   330          /*
   331           * Configure infrequently-changing library-wide settings.
   332           *
   333           * Accept an object or an argument list, with one or many of the following properties or
   334           * parameters respectively:
   335           *
   336           *   DECIMAL_PLACES  {number}  Integer, 0 to MAX inclusive
   337           *   ROUNDING_MODE   {number}  Integer, 0 to 8 inclusive
   338           *   EXPONENTIAL_AT  {number|number[]}  Integer, -MAX to MAX inclusive or
   339           *                                      [integer -MAX to 0 incl., 0 to MAX incl.]
   340           *   RANGE           {number|number[]}  Non-zero integer, -MAX to MAX inclusive or
   341           *                                      [integer -MAX to -1 incl., integer 1 to MAX incl.]
   342           *   ERRORS          {boolean|number}   true, false, 1 or 0
   343           *   CRYPTO          {boolean|number}   true, false, 1 or 0
   344           *   MODULO_MODE     {number}           0 to 9 inclusive
   345           *   POW_PRECISION   {number}           0 to MAX inclusive
   346           *   FORMAT          {object}           See BigNumber.prototype.toFormat
   347           *      decimalSeparator       {string}
   348           *      groupSeparator         {string}
   349           *      groupSize              {number}
   350           *      secondaryGroupSize     {number}
   351           *      fractionGroupSeparator {string}
   352           *      fractionGroupSize      {number}
   353           *
   354           * (The values assigned to the above FORMAT object properties are not checked for validity.)
   355           *
   356           * E.g.
   357           * BigNumber.config(20, 4) is equivalent to
   358           * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
   359           *
   360           * Ignore properties/parameters set to null or undefined.
   361           * Return an object with the properties current values.
   362           */
   363          BigNumber.config = function () {
   364              var v, p,
   365                  i = 0,
   366                  r = {},
   367                  a = arguments,
   368                  o = a[0],
   369                  has = o && typeof o == 'object'
   370                    ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
   371                    : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
   372  
   373              // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
   374              // 'config() DECIMAL_PLACES not an integer: {v}'
   375              // 'config() DECIMAL_PLACES out of range: {v}'
   376              if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
   377                  DECIMAL_PLACES = v | 0;
   378              }
   379              r[p] = DECIMAL_PLACES;
   380  
   381              // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
   382              // 'config() ROUNDING_MODE not an integer: {v}'
   383              // 'config() ROUNDING_MODE out of range: {v}'
   384              if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
   385                  ROUNDING_MODE = v | 0;
   386              }
   387              r[p] = ROUNDING_MODE;
   388  
   389              // EXPONENTIAL_AT {number|number[]}
   390              // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
   391              // 'config() EXPONENTIAL_AT not an integer: {v}'
   392              // 'config() EXPONENTIAL_AT out of range: {v}'
   393              if ( has( p = 'EXPONENTIAL_AT' ) ) {
   394  
   395                  if ( isArray(v) ) {
   396                      if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
   397                          TO_EXP_NEG = v[0] | 0;
   398                          TO_EXP_POS = v[1] | 0;
   399                      }
   400                  } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
   401                      TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
   402                  }
   403              }
   404              r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
   405  
   406              // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
   407              // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
   408              // 'config() RANGE not an integer: {v}'
   409              // 'config() RANGE cannot be zero: {v}'
   410              // 'config() RANGE out of range: {v}'
   411              if ( has( p = 'RANGE' ) ) {
   412  
   413                  if ( isArray(v) ) {
   414                      if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
   415                          MIN_EXP = v[0] | 0;
   416                          MAX_EXP = v[1] | 0;
   417                      }
   418                  } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
   419                      if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
   420                      else if (ERRORS) raise( 2, p + ' cannot be zero', v );
   421                  }
   422              }
   423              r[p] = [ MIN_EXP, MAX_EXP ];
   424  
   425              // ERRORS {boolean|number} true, false, 1 or 0.
   426              // 'config() ERRORS not a boolean or binary digit: {v}'
   427              if ( has( p = 'ERRORS' ) ) {
   428  
   429                  if ( v === !!v || v === 1 || v === 0 ) {
   430                      id = 0;
   431                      isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
   432                  } else if (ERRORS) {
   433                      raise( 2, p + notBool, v );
   434                  }
   435              }
   436              r[p] = ERRORS;
   437  
   438              // CRYPTO {boolean|number} true, false, 1 or 0.
   439              // 'config() CRYPTO not a boolean or binary digit: {v}'
   440              // 'config() crypto unavailable: {crypto}'
   441              if ( has( p = 'CRYPTO' ) ) {
   442  
   443                  if ( v === !!v || v === 1 || v === 0 ) {
   444                      CRYPTO = !!( v && crypto && typeof crypto == 'object' );
   445                      if ( v && !CRYPTO && ERRORS ) raise( 2, 'crypto unavailable', crypto );
   446                  } else if (ERRORS) {
   447                      raise( 2, p + notBool, v );
   448                  }
   449              }
   450              r[p] = CRYPTO;
   451  
   452              // MODULO_MODE {number} Integer, 0 to 9 inclusive.
   453              // 'config() MODULO_MODE not an integer: {v}'
   454              // 'config() MODULO_MODE out of range: {v}'
   455              if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
   456                  MODULO_MODE = v | 0;
   457              }
   458              r[p] = MODULO_MODE;
   459  
   460              // POW_PRECISION {number} Integer, 0 to MAX inclusive.
   461              // 'config() POW_PRECISION not an integer: {v}'
   462              // 'config() POW_PRECISION out of range: {v}'
   463              if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
   464                  POW_PRECISION = v | 0;
   465              }
   466              r[p] = POW_PRECISION;
   467  
   468              // FORMAT {object}
   469              // 'config() FORMAT not an object: {v}'
   470              if ( has( p = 'FORMAT' ) ) {
   471  
   472                  if ( typeof v == 'object' ) {
   473                      FORMAT = v;
   474                  } else if (ERRORS) {
   475                      raise( 2, p + ' not an object', v );
   476                  }
   477              }
   478              r[p] = FORMAT;
   479  
   480              return r;
   481          };
   482  
   483  
   484          /*
   485           * Return a new BigNumber whose value is the maximum of the arguments.
   486           *
   487           * arguments {number|string|BigNumber}
   488           */
   489          BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
   490  
   491  
   492          /*
   493           * Return a new BigNumber whose value is the minimum of the arguments.
   494           *
   495           * arguments {number|string|BigNumber}
   496           */
   497          BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
   498  
   499  
   500          /*
   501           * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
   502           * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
   503           * zeros are produced).
   504           *
   505           * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
   506           *
   507           * 'random() decimal places not an integer: {dp}'
   508           * 'random() decimal places out of range: {dp}'
   509           * 'random() crypto unavailable: {crypto}'
   510           */
   511          BigNumber.random = (function () {
   512              var pow2_53 = 0x20000000000000;
   513  
   514              // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
   515              // Check if Math.random() produces more than 32 bits of randomness.
   516              // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
   517              // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
   518              var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
   519                ? function () { return mathfloor( Math.random() * pow2_53 ); }
   520                : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
   521                    (Math.random() * 0x800000 | 0); };
   522  
   523              return function (dp) {
   524                  var a, b, e, k, v,
   525                      i = 0,
   526                      c = [],
   527                      rand = new BigNumber(ONE);
   528  
   529                  dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
   530                  k = mathceil( dp / LOG_BASE );
   531  
   532                  if (CRYPTO) {
   533  
   534                      // Browsers supporting crypto.getRandomValues.
   535                      if ( crypto && crypto.getRandomValues ) {
   536  
   537                          a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
   538  
   539                          for ( ; i < k; ) {
   540  
   541                              // 53 bits:
   542                              // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
   543                              // 11111 11111111 11111111 11111111 11100000 00000000 00000000
   544                              // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
   545                              //                                     11111 11111111 11111111
   546                              // 0x20000 is 2^21.
   547                              v = a[i] * 0x20000 + (a[i + 1] >>> 11);
   548  
   549                              // Rejection sampling:
   550                              // 0 <= v < 9007199254740992
   551                              // Probability that v >= 9e15, is
   552                              // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
   553                              if ( v >= 9e15 ) {
   554                                  b = crypto.getRandomValues( new Uint32Array(2) );
   555                                  a[i] = b[0];
   556                                  a[i + 1] = b[1];
   557                              } else {
   558  
   559                                  // 0 <= v <= 8999999999999999
   560                                  // 0 <= (v % 1e14) <= 99999999999999
   561                                  c.push( v % 1e14 );
   562                                  i += 2;
   563                              }
   564                          }
   565                          i = k / 2;
   566  
   567                      // Node.js supporting crypto.randomBytes.
   568                      } else if ( crypto && crypto.randomBytes ) {
   569  
   570                          // buffer
   571                          a = crypto.randomBytes( k *= 7 );
   572  
   573                          for ( ; i < k; ) {
   574  
   575                              // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
   576                              // 0x100000000 is 2^32, 0x1000000 is 2^24
   577                              // 11111 11111111 11111111 11111111 11111111 11111111 11111111
   578                              // 0 <= v < 9007199254740992
   579                              v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
   580                                    ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
   581                                    ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
   582  
   583                              if ( v >= 9e15 ) {
   584                                  crypto.randomBytes(7).copy( a, i );
   585                              } else {
   586  
   587                                  // 0 <= (v % 1e14) <= 99999999999999
   588                                  c.push( v % 1e14 );
   589                                  i += 7;
   590                              }
   591                          }
   592                          i = k / 7;
   593                      } else if (ERRORS) {
   594                          raise( 14, 'crypto unavailable', crypto );
   595                      }
   596                  }
   597  
   598                  // Use Math.random: CRYPTO is false or crypto is unavailable and ERRORS is false.
   599                  if (!i) {
   600  
   601                      for ( ; i < k; ) {
   602                          v = random53bitInt();
   603                          if ( v < 9e15 ) c[i++] = v % 1e14;
   604                      }
   605                  }
   606  
   607                  k = c[--i];
   608                  dp %= LOG_BASE;
   609  
   610                  // Convert trailing digits to zeros according to dp.
   611                  if ( k && dp ) {
   612                      v = POWS_TEN[LOG_BASE - dp];
   613                      c[i] = mathfloor( k / v ) * v;
   614                  }
   615  
   616                  // Remove trailing elements which are zero.
   617                  for ( ; c[i] === 0; c.pop(), i-- );
   618  
   619                  // Zero?
   620                  if ( i < 0 ) {
   621                      c = [ e = 0 ];
   622                  } else {
   623  
   624                      // Remove leading elements which are zero and adjust exponent accordingly.
   625                      for ( e = -1 ; c[0] === 0; c.shift(), e -= LOG_BASE);
   626  
   627                      // Count the digits of the first element of c to determine leading zeros, and...
   628                      for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
   629  
   630                      // adjust the exponent accordingly.
   631                      if ( i < LOG_BASE ) e -= LOG_BASE - i;
   632                  }
   633  
   634                  rand.e = e;
   635                  rand.c = c;
   636                  return rand;
   637              };
   638          })();
   639  
   640  
   641          // PRIVATE FUNCTIONS
   642  
   643  
   644          // Convert a numeric string of baseIn to a numeric string of baseOut.
   645          function convertBase( str, baseOut, baseIn, sign ) {
   646              var d, e, k, r, x, xc, y,
   647                  i = str.indexOf( '.' ),
   648                  dp = DECIMAL_PLACES,
   649                  rm = ROUNDING_MODE;
   650  
   651              if ( baseIn < 37 ) str = str.toLowerCase();
   652  
   653              // Non-integer.
   654              if ( i >= 0 ) {
   655                  k = POW_PRECISION;
   656  
   657                  // Unlimited precision.
   658                  POW_PRECISION = 0;
   659                  str = str.replace( '.', '' );
   660                  y = new BigNumber(baseIn);
   661                  x = y.pow( str.length - i );
   662                  POW_PRECISION = k;
   663  
   664                  // Convert str as if an integer, then restore the fraction part by dividing the
   665                  // result by its base raised to a power.
   666                  y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
   667                  y.e = y.c.length;
   668              }
   669  
   670              // Convert the number as integer.
   671              xc = toBaseOut( str, baseIn, baseOut );
   672              e = k = xc.length;
   673  
   674              // Remove trailing zeros.
   675              for ( ; xc[--k] == 0; xc.pop() );
   676              if ( !xc[0] ) return '0';
   677  
   678              if ( i < 0 ) {
   679                  --e;
   680              } else {
   681                  x.c = xc;
   682                  x.e = e;
   683  
   684                  // sign is needed for correct rounding.
   685                  x.s = sign;
   686                  x = div( x, y, dp, rm, baseOut );
   687                  xc = x.c;
   688                  r = x.r;
   689                  e = x.e;
   690              }
   691  
   692              d = e + dp + 1;
   693  
   694              // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
   695              i = xc[d];
   696              k = baseOut / 2;
   697              r = r || d < 0 || xc[d + 1] != null;
   698  
   699              r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
   700                         : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
   701                           rm == ( x.s < 0 ? 8 : 7 ) );
   702  
   703              if ( d < 1 || !xc[0] ) {
   704  
   705                  // 1^-dp or 0.
   706                  str = r ? toFixedPoint( '1', -dp ) : '0';
   707              } else {
   708                  xc.length = d;
   709  
   710                  if (r) {
   711  
   712                      // Rounding up may mean the previous digit has to be rounded up and so on.
   713                      for ( --baseOut; ++xc[--d] > baseOut; ) {
   714                          xc[d] = 0;
   715  
   716                          if ( !d ) {
   717                              ++e;
   718                              xc.unshift(1);
   719                          }
   720                      }
   721                  }
   722  
   723                  // Determine trailing zeros.
   724                  for ( k = xc.length; !xc[--k]; );
   725  
   726                  // E.g. [4, 11, 15] becomes 4bf.
   727                  for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
   728                  str = toFixedPoint( str, e );
   729              }
   730  
   731              // The caller will add the sign.
   732              return str;
   733          }
   734  
   735  
   736          // Perform division in the specified base. Called by div and convertBase.
   737          div = (function () {
   738  
   739              // Assume non-zero x and k.
   740              function multiply( x, k, base ) {
   741                  var m, temp, xlo, xhi,
   742                      carry = 0,
   743                      i = x.length,
   744                      klo = k % SQRT_BASE,
   745                      khi = k / SQRT_BASE | 0;
   746  
   747                  for ( x = x.slice(); i--; ) {
   748                      xlo = x[i] % SQRT_BASE;
   749                      xhi = x[i] / SQRT_BASE | 0;
   750                      m = khi * xlo + xhi * klo;
   751                      temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
   752                      carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
   753                      x[i] = temp % base;
   754                  }
   755  
   756                  if (carry) x.unshift(carry);
   757  
   758                  return x;
   759              }
   760  
   761              function compare( a, b, aL, bL ) {
   762                  var i, cmp;
   763  
   764                  if ( aL != bL ) {
   765                      cmp = aL > bL ? 1 : -1;
   766                  } else {
   767  
   768                      for ( i = cmp = 0; i < aL; i++ ) {
   769  
   770                          if ( a[i] != b[i] ) {
   771                              cmp = a[i] > b[i] ? 1 : -1;
   772                              break;
   773                          }
   774                      }
   775                  }
   776                  return cmp;
   777              }
   778  
   779              function subtract( a, b, aL, base ) {
   780                  var i = 0;
   781  
   782                  // Subtract b from a.
   783                  for ( ; aL--; ) {
   784                      a[aL] -= i;
   785                      i = a[aL] < b[aL] ? 1 : 0;
   786                      a[aL] = i * base + a[aL] - b[aL];
   787                  }
   788  
   789                  // Remove leading zeros.
   790                  for ( ; !a[0] && a.length > 1; a.shift() );
   791              }
   792  
   793              // x: dividend, y: divisor.
   794              return function ( x, y, dp, rm, base ) {
   795                  var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
   796                      yL, yz,
   797                      s = x.s == y.s ? 1 : -1,
   798                      xc = x.c,
   799                      yc = y.c;
   800  
   801                  // Either NaN, Infinity or 0?
   802                  if ( !xc || !xc[0] || !yc || !yc[0] ) {
   803  
   804                      return new BigNumber(
   805  
   806                        // Return NaN if either NaN, or both Infinity or 0.
   807                        !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
   808  
   809                          // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
   810                          xc && xc[0] == 0 || !yc ? s * 0 : s / 0
   811                      );
   812                  }
   813  
   814                  q = new BigNumber(s);
   815                  qc = q.c = [];
   816                  e = x.e - y.e;
   817                  s = dp + e + 1;
   818  
   819                  if ( !base ) {
   820                      base = BASE;
   821                      e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
   822                      s = s / LOG_BASE | 0;
   823                  }
   824  
   825                  // Result exponent may be one less then the current value of e.
   826                  // The coefficients of the BigNumbers from convertBase may have trailing zeros.
   827                  for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
   828                  if ( yc[i] > ( xc[i] || 0 ) ) e--;
   829  
   830                  if ( s < 0 ) {
   831                      qc.push(1);
   832                      more = true;
   833                  } else {
   834                      xL = xc.length;
   835                      yL = yc.length;
   836                      i = 0;
   837                      s += 2;
   838  
   839                      // Normalise xc and yc so highest order digit of yc is >= base / 2.
   840  
   841                      n = mathfloor( base / ( yc[0] + 1 ) );
   842  
   843                      // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
   844                      // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
   845                      if ( n > 1 ) {
   846                          yc = multiply( yc, n, base );
   847                          xc = multiply( xc, n, base );
   848                          yL = yc.length;
   849                          xL = xc.length;
   850                      }
   851  
   852                      xi = yL;
   853                      rem = xc.slice( 0, yL );
   854                      remL = rem.length;
   855  
   856                      // Add zeros to make remainder as long as divisor.
   857                      for ( ; remL < yL; rem[remL++] = 0 );
   858                      yz = yc.slice();
   859                      yz.unshift(0);
   860                      yc0 = yc[0];
   861                      if ( yc[1] >= base / 2 ) yc0++;
   862                      // Not necessary, but to prevent trial digit n > base, when using base 3.
   863                      // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
   864  
   865                      do {
   866                          n = 0;
   867  
   868                          // Compare divisor and remainder.
   869                          cmp = compare( yc, rem, yL, remL );
   870  
   871                          // If divisor < remainder.
   872                          if ( cmp < 0 ) {
   873  
   874                              // Calculate trial digit, n.
   875  
   876                              rem0 = rem[0];
   877                              if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
   878  
   879                              // n is how many times the divisor goes into the current remainder.
   880                              n = mathfloor( rem0 / yc0 );
   881  
   882                              //  Algorithm:
   883                              //  1. product = divisor * trial digit (n)
   884                              //  2. if product > remainder: product -= divisor, n--
   885                              //  3. remainder -= product
   886                              //  4. if product was < remainder at 2:
   887                              //    5. compare new remainder and divisor
   888                              //    6. If remainder > divisor: remainder -= divisor, n++
   889  
   890                              if ( n > 1 ) {
   891  
   892                                  // n may be > base only when base is 3.
   893                                  if (n >= base) n = base - 1;
   894  
   895                                  // product = divisor * trial digit.
   896                                  prod = multiply( yc, n, base );
   897                                  prodL = prod.length;
   898                                  remL = rem.length;
   899  
   900                                  // Compare product and remainder.
   901                                  // If product > remainder.
   902                                  // Trial digit n too high.
   903                                  // n is 1 too high about 5% of the time, and is not known to have
   904                                  // ever been more than 1 too high.
   905                                  while ( compare( prod, rem, prodL, remL ) == 1 ) {
   906                                      n--;
   907  
   908                                      // Subtract divisor from product.
   909                                      subtract( prod, yL < prodL ? yz : yc, prodL, base );
   910                                      prodL = prod.length;
   911                                      cmp = 1;
   912                                  }
   913                              } else {
   914  
   915                                  // n is 0 or 1, cmp is -1.
   916                                  // If n is 0, there is no need to compare yc and rem again below,
   917                                  // so change cmp to 1 to avoid it.
   918                                  // If n is 1, leave cmp as -1, so yc and rem are compared again.
   919                                  if ( n == 0 ) {
   920  
   921                                      // divisor < remainder, so n must be at least 1.
   922                                      cmp = n = 1;
   923                                  }
   924  
   925                                  // product = divisor
   926                                  prod = yc.slice();
   927                                  prodL = prod.length;
   928                              }
   929  
   930                              if ( prodL < remL ) prod.unshift(0);
   931  
   932                              // Subtract product from remainder.
   933                              subtract( rem, prod, remL, base );
   934                              remL = rem.length;
   935  
   936                               // If product was < remainder.
   937                              if ( cmp == -1 ) {
   938  
   939                                  // Compare divisor and new remainder.
   940                                  // If divisor < new remainder, subtract divisor from remainder.
   941                                  // Trial digit n too low.
   942                                  // n is 1 too low about 5% of the time, and very rarely 2 too low.
   943                                  while ( compare( yc, rem, yL, remL ) < 1 ) {
   944                                      n++;
   945  
   946                                      // Subtract divisor from remainder.
   947                                      subtract( rem, yL < remL ? yz : yc, remL, base );
   948                                      remL = rem.length;
   949                                  }
   950                              }
   951                          } else if ( cmp === 0 ) {
   952                              n++;
   953                              rem = [0];
   954                          } // else cmp === 1 and n will be 0
   955  
   956                          // Add the next digit, n, to the result array.
   957                          qc[i++] = n;
   958  
   959                          // Update the remainder.
   960                          if ( rem[0] ) {
   961                              rem[remL++] = xc[xi] || 0;
   962                          } else {
   963                              rem = [ xc[xi] ];
   964                              remL = 1;
   965                          }
   966                      } while ( ( xi++ < xL || rem[0] != null ) && s-- );
   967  
   968                      more = rem[0] != null;
   969  
   970                      // Leading zero?
   971                      if ( !qc[0] ) qc.shift();
   972                  }
   973  
   974                  if ( base == BASE ) {
   975  
   976                      // To calculate q.e, first get the number of digits of qc[0].
   977                      for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
   978                      round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
   979  
   980                  // Caller is convertBase.
   981                  } else {
   982                      q.e = e;
   983                      q.r = +more;
   984                  }
   985  
   986                  return q;
   987              };
   988          })();
   989  
   990  
   991          /*
   992           * Return a string representing the value of BigNumber n in fixed-point or exponential
   993           * notation rounded to the specified decimal places or significant digits.
   994           *
   995           * n is a BigNumber.
   996           * i is the index of the last digit required (i.e. the digit that may be rounded up).
   997           * rm is the rounding mode.
   998           * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
   999           */
  1000          function format( n, i, rm, caller ) {
  1001              var c0, e, ne, len, str;
  1002  
  1003              rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
  1004                ? rm | 0 : ROUNDING_MODE;
  1005  
  1006              if ( !n.c ) return n.toString();
  1007              c0 = n.c[0];
  1008              ne = n.e;
  1009  
  1010              if ( i == null ) {
  1011                  str = coeffToString( n.c );
  1012                  str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
  1013                    ? toExponential( str, ne )
  1014                    : toFixedPoint( str, ne );
  1015              } else {
  1016                  n = round( new BigNumber(n), i, rm );
  1017  
  1018                  // n.e may have changed if the value was rounded up.
  1019                  e = n.e;
  1020  
  1021                  str = coeffToString( n.c );
  1022                  len = str.length;
  1023  
  1024                  // toPrecision returns exponential notation if the number of significant digits
  1025                  // specified is less than the number of digits necessary to represent the integer
  1026                  // part of the value in fixed-point notation.
  1027  
  1028                  // Exponential notation.
  1029                  if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
  1030  
  1031                      // Append zeros?
  1032                      for ( ; len < i; str += '0', len++ );
  1033                      str = toExponential( str, e );
  1034  
  1035                  // Fixed-point notation.
  1036                  } else {
  1037                      i -= ne;
  1038                      str = toFixedPoint( str, e );
  1039  
  1040                      // Append zeros?
  1041                      if ( e + 1 > len ) {
  1042                          if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
  1043                      } else {
  1044                          i += e - len;
  1045                          if ( i > 0 ) {
  1046                              if ( e + 1 == len ) str += '.';
  1047                              for ( ; i--; str += '0' );
  1048                          }
  1049                      }
  1050                  }
  1051              }
  1052  
  1053              return n.s < 0 && c0 ? '-' + str : str;
  1054          }
  1055  
  1056  
  1057          // Handle BigNumber.max and BigNumber.min.
  1058          function maxOrMin( args, method ) {
  1059              var m, n,
  1060                  i = 0;
  1061  
  1062              if ( isArray( args[0] ) ) args = args[0];
  1063              m = new BigNumber( args[0] );
  1064  
  1065              for ( ; ++i < args.length; ) {
  1066                  n = new BigNumber( args[i] );
  1067  
  1068                  // If any number is NaN, return NaN.
  1069                  if ( !n.s ) {
  1070                      m = n;
  1071                      break;
  1072                  } else if ( method.call( m, n ) ) {
  1073                      m = n;
  1074                  }
  1075              }
  1076  
  1077              return m;
  1078          }
  1079  
  1080  
  1081          /*
  1082           * Return true if n is an integer in range, otherwise throw.
  1083           * Use for argument validation when ERRORS is true.
  1084           */
  1085          function intValidatorWithErrors( n, min, max, caller, name ) {
  1086              if ( n < min || n > max || n != truncate(n) ) {
  1087                  raise( caller, ( name || 'decimal places' ) +
  1088                    ( n < min || n > max ? ' out of range' : ' not an integer' ), n );
  1089              }
  1090  
  1091              return true;
  1092          }
  1093  
  1094  
  1095          /*
  1096           * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
  1097           * Called by minus, plus and times.
  1098           */
  1099          function normalise( n, c, e ) {
  1100              var i = 1,
  1101                  j = c.length;
  1102  
  1103               // Remove trailing zeros.
  1104              for ( ; !c[--j]; c.pop() );
  1105  
  1106              // Calculate the base 10 exponent. First get the number of digits of c[0].
  1107              for ( j = c[0]; j >= 10; j /= 10, i++ );
  1108  
  1109              // Overflow?
  1110              if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
  1111  
  1112                  // Infinity.
  1113                  n.c = n.e = null;
  1114  
  1115              // Underflow?
  1116              } else if ( e < MIN_EXP ) {
  1117  
  1118                  // Zero.
  1119                  n.c = [ n.e = 0 ];
  1120              } else {
  1121                  n.e = e;
  1122                  n.c = c;
  1123              }
  1124  
  1125              return n;
  1126          }
  1127  
  1128  
  1129          // Handle values that fail the validity test in BigNumber.
  1130          parseNumeric = (function () {
  1131              var basePrefix = /^(-?)0([xbo])/i,
  1132                  dotAfter = /^([^.]+)\.$/,
  1133                  dotBefore = /^\.([^.]+)$/,
  1134                  isInfinityOrNaN = /^-?(Infinity|NaN)$/,
  1135                  whitespaceOrPlus = /^\s*\+|^\s+|\s+$/g;
  1136  
  1137              return function ( x, str, num, b ) {
  1138                  var base,
  1139                      s = num ? str : str.replace( whitespaceOrPlus, '' );
  1140  
  1141                  // No exception on ±Infinity or NaN.
  1142                  if ( isInfinityOrNaN.test(s) ) {
  1143                      x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
  1144                  } else {
  1145                      if ( !num ) {
  1146  
  1147                          // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
  1148                          s = s.replace( basePrefix, function ( m, p1, p2 ) {
  1149                              base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
  1150                              return !b || b == base ? p1 : m;
  1151                          });
  1152  
  1153                          if (b) {
  1154                              base = b;
  1155  
  1156                              // E.g. '1.' to '1', '.1' to '0.1'
  1157                              s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
  1158                          }
  1159  
  1160                          if ( str != s ) return new BigNumber( s, base );
  1161                      }
  1162  
  1163                      // 'new BigNumber() not a number: {n}'
  1164                      // 'new BigNumber() not a base {b} number: {n}'
  1165                      if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
  1166                      x.s = null;
  1167                  }
  1168  
  1169                  x.c = x.e = null;
  1170                  id = 0;
  1171              }
  1172          })();
  1173  
  1174  
  1175          // Throw a BigNumber Error.
  1176          function raise( caller, msg, val ) {
  1177              var error = new Error( [
  1178                  'new BigNumber',     // 0
  1179                  'cmp',               // 1
  1180                  'config',            // 2
  1181                  'div',               // 3
  1182                  'divToInt',          // 4
  1183                  'eq',                // 5
  1184                  'gt',                // 6
  1185                  'gte',               // 7
  1186                  'lt',                // 8
  1187                  'lte',               // 9
  1188                  'minus',             // 10
  1189                  'mod',               // 11
  1190                  'plus',              // 12
  1191                  'precision',         // 13
  1192                  'random',            // 14
  1193                  'round',             // 15
  1194                  'shift',             // 16
  1195                  'times',             // 17
  1196                  'toDigits',          // 18
  1197                  'toExponential',     // 19
  1198                  'toFixed',           // 20
  1199                  'toFormat',          // 21
  1200                  'toFraction',        // 22
  1201                  'pow',               // 23
  1202                  'toPrecision',       // 24
  1203                  'toString',          // 25
  1204                  'BigNumber'          // 26
  1205              ][caller] + '() ' + msg + ': ' + val );
  1206  
  1207              error.name = 'BigNumber Error';
  1208              id = 0;
  1209              throw error;
  1210          }
  1211  
  1212  
  1213          /*
  1214           * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
  1215           * If r is truthy, it is known that there are more digits after the rounding digit.
  1216           */
  1217          function round( x, sd, rm, r ) {
  1218              var d, i, j, k, n, ni, rd,
  1219                  xc = x.c,
  1220                  pows10 = POWS_TEN;
  1221  
  1222              // if x is not Infinity or NaN...
  1223              if (xc) {
  1224  
  1225                  // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
  1226                  // n is a base 1e14 number, the value of the element of array x.c containing rd.
  1227                  // ni is the index of n within x.c.
  1228                  // d is the number of digits of n.
  1229                  // i is the index of rd within n including leading zeros.
  1230                  // j is the actual index of rd within n (if < 0, rd is a leading zero).
  1231                  out: {
  1232  
  1233                      // Get the number of digits of the first element of xc.
  1234                      for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
  1235                      i = sd - d;
  1236  
  1237                      // If the rounding digit is in the first element of xc...
  1238                      if ( i < 0 ) {
  1239                          i += LOG_BASE;
  1240                          j = sd;
  1241                          n = xc[ ni = 0 ];
  1242  
  1243                          // Get the rounding digit at index j of n.
  1244                          rd = n / pows10[ d - j - 1 ] % 10 | 0;
  1245                      } else {
  1246                          ni = mathceil( ( i + 1 ) / LOG_BASE );
  1247  
  1248                          if ( ni >= xc.length ) {
  1249  
  1250                              if (r) {
  1251  
  1252                                  // Needed by sqrt.
  1253                                  for ( ; xc.length <= ni; xc.push(0) );
  1254                                  n = rd = 0;
  1255                                  d = 1;
  1256                                  i %= LOG_BASE;
  1257                                  j = i - LOG_BASE + 1;
  1258                              } else {
  1259                                  break out;
  1260                              }
  1261                          } else {
  1262                              n = k = xc[ni];
  1263  
  1264                              // Get the number of digits of n.
  1265                              for ( d = 1; k >= 10; k /= 10, d++ );
  1266  
  1267                              // Get the index of rd within n.
  1268                              i %= LOG_BASE;
  1269  
  1270                              // Get the index of rd within n, adjusted for leading zeros.
  1271                              // The number of leading zeros of n is given by LOG_BASE - d.
  1272                              j = i - LOG_BASE + d;
  1273  
  1274                              // Get the rounding digit at index j of n.
  1275                              rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
  1276                          }
  1277                      }
  1278  
  1279                      r = r || sd < 0 ||
  1280  
  1281                      // Are there any non-zero digits after the rounding digit?
  1282                      // The expression  n % pows10[ d - j - 1 ]  returns all digits of n to the right
  1283                      // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
  1284                        xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
  1285  
  1286                      r = rm < 4
  1287                        ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
  1288                        : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
  1289  
  1290                          // Check whether the digit to the left of the rounding digit is odd.
  1291                          ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
  1292                            rm == ( x.s < 0 ? 8 : 7 ) );
  1293  
  1294                      if ( sd < 1 || !xc[0] ) {
  1295                          xc.length = 0;
  1296  
  1297                          if (r) {
  1298  
  1299                              // Convert sd to decimal places.
  1300                              sd -= x.e + 1;
  1301  
  1302                              // 1, 0.1, 0.01, 0.001, 0.0001 etc.
  1303                              xc[0] = pows10[ sd % LOG_BASE ];
  1304                              x.e = -sd || 0;
  1305                          } else {
  1306  
  1307                              // Zero.
  1308                              xc[0] = x.e = 0;
  1309                          }
  1310  
  1311                          return x;
  1312                      }
  1313  
  1314                      // Remove excess digits.
  1315                      if ( i == 0 ) {
  1316                          xc.length = ni;
  1317                          k = 1;
  1318                          ni--;
  1319                      } else {
  1320                          xc.length = ni + 1;
  1321                          k = pows10[ LOG_BASE - i ];
  1322  
  1323                          // E.g. 56700 becomes 56000 if 7 is the rounding digit.
  1324                          // j > 0 means i > number of leading zeros of n.
  1325                          xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
  1326                      }
  1327  
  1328                      // Round up?
  1329                      if (r) {
  1330  
  1331                          for ( ; ; ) {
  1332  
  1333                              // If the digit to be rounded up is in the first element of xc...
  1334                              if ( ni == 0 ) {
  1335  
  1336                                  // i will be the length of xc[0] before k is added.
  1337                                  for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
  1338                                  j = xc[0] += k;
  1339                                  for ( k = 1; j >= 10; j /= 10, k++ );
  1340  
  1341                                  // if i != k the length has increased.
  1342                                  if ( i != k ) {
  1343                                      x.e++;
  1344                                      if ( xc[0] == BASE ) xc[0] = 1;
  1345                                  }
  1346  
  1347                                  break;
  1348                              } else {
  1349                                  xc[ni] += k;
  1350                                  if ( xc[ni] != BASE ) break;
  1351                                  xc[ni--] = 0;
  1352                                  k = 1;
  1353                              }
  1354                          }
  1355                      }
  1356  
  1357                      // Remove trailing zeros.
  1358                      for ( i = xc.length; xc[--i] === 0; xc.pop() );
  1359                  }
  1360  
  1361                  // Overflow? Infinity.
  1362                  if ( x.e > MAX_EXP ) {
  1363                      x.c = x.e = null;
  1364  
  1365                  // Underflow? Zero.
  1366                  } else if ( x.e < MIN_EXP ) {
  1367                      x.c = [ x.e = 0 ];
  1368                  }
  1369              }
  1370  
  1371              return x;
  1372          }
  1373  
  1374  
  1375          // PROTOTYPE/INSTANCE METHODS
  1376  
  1377  
  1378          /*
  1379           * Return a new BigNumber whose value is the absolute value of this BigNumber.
  1380           */
  1381          P.absoluteValue = P.abs = function () {
  1382              var x = new BigNumber(this);
  1383              if ( x.s < 0 ) x.s = 1;
  1384              return x;
  1385          };
  1386  
  1387  
  1388          /*
  1389           * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
  1390           * number in the direction of Infinity.
  1391           */
  1392          P.ceil = function () {
  1393              return round( new BigNumber(this), this.e + 1, 2 );
  1394          };
  1395  
  1396  
  1397          /*
  1398           * Return
  1399           * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
  1400           * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
  1401           * 0 if they have the same value,
  1402           * or null if the value of either is NaN.
  1403           */
  1404          P.comparedTo = P.cmp = function ( y, b ) {
  1405              id = 1;
  1406              return compare( this, new BigNumber( y, b ) );
  1407          };
  1408  
  1409  
  1410          /*
  1411           * Return the number of decimal places of the value of this BigNumber, or null if the value
  1412           * of this BigNumber is ±Infinity or NaN.
  1413           */
  1414          P.decimalPlaces = P.dp = function () {
  1415              var n, v,
  1416                  c = this.c;
  1417  
  1418              if ( !c ) return null;
  1419              n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
  1420  
  1421              // Subtract the number of trailing zeros of the last number.
  1422              if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
  1423              if ( n < 0 ) n = 0;
  1424  
  1425              return n;
  1426          };
  1427  
  1428  
  1429          /*
  1430           *  n / 0 = I
  1431           *  n / N = N
  1432           *  n / I = 0
  1433           *  0 / n = 0
  1434           *  0 / 0 = N
  1435           *  0 / N = N
  1436           *  0 / I = 0
  1437           *  N / n = N
  1438           *  N / 0 = N
  1439           *  N / N = N
  1440           *  N / I = N
  1441           *  I / n = I
  1442           *  I / 0 = I
  1443           *  I / N = N
  1444           *  I / I = N
  1445           *
  1446           * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
  1447           * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
  1448           */
  1449          P.dividedBy = P.div = function ( y, b ) {
  1450              id = 3;
  1451              return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
  1452          };
  1453  
  1454  
  1455          /*
  1456           * Return a new BigNumber whose value is the integer part of dividing the value of this
  1457           * BigNumber by the value of BigNumber(y, b).
  1458           */
  1459          P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
  1460              id = 4;
  1461              return div( this, new BigNumber( y, b ), 0, 1 );
  1462          };
  1463  
  1464  
  1465          /*
  1466           * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
  1467           * otherwise returns false.
  1468           */
  1469          P.equals = P.eq = function ( y, b ) {
  1470              id = 5;
  1471              return compare( this, new BigNumber( y, b ) ) === 0;
  1472          };
  1473  
  1474  
  1475          /*
  1476           * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
  1477           * number in the direction of -Infinity.
  1478           */
  1479          P.floor = function () {
  1480              return round( new BigNumber(this), this.e + 1, 3 );
  1481          };
  1482  
  1483  
  1484          /*
  1485           * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
  1486           * otherwise returns false.
  1487           */
  1488          P.greaterThan = P.gt = function ( y, b ) {
  1489              id = 6;
  1490              return compare( this, new BigNumber( y, b ) ) > 0;
  1491          };
  1492  
  1493  
  1494          /*
  1495           * Return true if the value of this BigNumber is greater than or equal to the value of
  1496           * BigNumber(y, b), otherwise returns false.
  1497           */
  1498          P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
  1499              id = 7;
  1500              return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
  1501  
  1502          };
  1503  
  1504  
  1505          /*
  1506           * Return true if the value of this BigNumber is a finite number, otherwise returns false.
  1507           */
  1508          P.isFinite = function () {
  1509              return !!this.c;
  1510          };
  1511  
  1512  
  1513          /*
  1514           * Return true if the value of this BigNumber is an integer, otherwise return false.
  1515           */
  1516          P.isInteger = P.isInt = function () {
  1517              return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
  1518          };
  1519  
  1520  
  1521          /*
  1522           * Return true if the value of this BigNumber is NaN, otherwise returns false.
  1523           */
  1524          P.isNaN = function () {
  1525              return !this.s;
  1526          };
  1527  
  1528  
  1529          /*
  1530           * Return true if the value of this BigNumber is negative, otherwise returns false.
  1531           */
  1532          P.isNegative = P.isNeg = function () {
  1533              return this.s < 0;
  1534          };
  1535  
  1536  
  1537          /*
  1538           * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
  1539           */
  1540          P.isZero = function () {
  1541              return !!this.c && this.c[0] == 0;
  1542          };
  1543  
  1544  
  1545          /*
  1546           * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
  1547           * otherwise returns false.
  1548           */
  1549          P.lessThan = P.lt = function ( y, b ) {
  1550              id = 8;
  1551              return compare( this, new BigNumber( y, b ) ) < 0;
  1552          };
  1553  
  1554  
  1555          /*
  1556           * Return true if the value of this BigNumber is less than or equal to the value of
  1557           * BigNumber(y, b), otherwise returns false.
  1558           */
  1559          P.lessThanOrEqualTo = P.lte = function ( y, b ) {
  1560              id = 9;
  1561              return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
  1562          };
  1563  
  1564  
  1565          /*
  1566           *  n - 0 = n
  1567           *  n - N = N
  1568           *  n - I = -I
  1569           *  0 - n = -n
  1570           *  0 - 0 = 0
  1571           *  0 - N = N
  1572           *  0 - I = -I
  1573           *  N - n = N
  1574           *  N - 0 = N
  1575           *  N - N = N
  1576           *  N - I = N
  1577           *  I - n = I
  1578           *  I - 0 = I
  1579           *  I - N = N
  1580           *  I - I = N
  1581           *
  1582           * Return a new BigNumber whose value is the value of this BigNumber minus the value of
  1583           * BigNumber(y, b).
  1584           */
  1585          P.minus = P.sub = function ( y, b ) {
  1586              var i, j, t, xLTy,
  1587                  x = this,
  1588                  a = x.s;
  1589  
  1590              id = 10;
  1591              y = new BigNumber( y, b );
  1592              b = y.s;
  1593  
  1594              // Either NaN?
  1595              if ( !a || !b ) return new BigNumber(NaN);
  1596  
  1597              // Signs differ?
  1598              if ( a != b ) {
  1599                  y.s = -b;
  1600                  return x.plus(y);
  1601              }
  1602  
  1603              var xe = x.e / LOG_BASE,
  1604                  ye = y.e / LOG_BASE,
  1605                  xc = x.c,
  1606                  yc = y.c;
  1607  
  1608              if ( !xe || !ye ) {
  1609  
  1610                  // Either Infinity?
  1611                  if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
  1612  
  1613                  // Either zero?
  1614                  if ( !xc[0] || !yc[0] ) {
  1615  
  1616                      // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
  1617                      return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
  1618  
  1619                        // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
  1620                        ROUNDING_MODE == 3 ? -0 : 0 );
  1621                  }
  1622              }
  1623  
  1624              xe = bitFloor(xe);
  1625              ye = bitFloor(ye);
  1626              xc = xc.slice();
  1627  
  1628              // Determine which is the bigger number.
  1629              if ( a = xe - ye ) {
  1630  
  1631                  if ( xLTy = a < 0 ) {
  1632                      a = -a;
  1633                      t = xc;
  1634                  } else {
  1635                      ye = xe;
  1636                      t = yc;
  1637                  }
  1638  
  1639                  t.reverse();
  1640  
  1641                  // Prepend zeros to equalise exponents.
  1642                  for ( b = a; b--; t.push(0) );
  1643                  t.reverse();
  1644              } else {
  1645  
  1646                  // Exponents equal. Check digit by digit.
  1647                  j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
  1648  
  1649                  for ( a = b = 0; b < j; b++ ) {
  1650  
  1651                      if ( xc[b] != yc[b] ) {
  1652                          xLTy = xc[b] < yc[b];
  1653                          break;
  1654                      }
  1655                  }
  1656              }
  1657  
  1658              // x < y? Point xc to the array of the bigger number.
  1659              if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
  1660  
  1661              b = ( j = yc.length ) - ( i = xc.length );
  1662  
  1663              // Append zeros to xc if shorter.
  1664              // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
  1665              if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
  1666              b = BASE - 1;
  1667  
  1668              // Subtract yc from xc.
  1669              for ( ; j > a; ) {
  1670  
  1671                  if ( xc[--j] < yc[j] ) {
  1672                      for ( i = j; i && !xc[--i]; xc[i] = b );
  1673                      --xc[i];
  1674                      xc[j] += BASE;
  1675                  }
  1676  
  1677                  xc[j] -= yc[j];
  1678              }
  1679  
  1680              // Remove leading zeros and adjust exponent accordingly.
  1681              for ( ; xc[0] == 0; xc.shift(), --ye );
  1682  
  1683              // Zero?
  1684              if ( !xc[0] ) {
  1685  
  1686                  // Following IEEE 754 (2008) 6.3,
  1687                  // n - n = +0  but  n - n = -0  when rounding towards -Infinity.
  1688                  y.s = ROUNDING_MODE == 3 ? -1 : 1;
  1689                  y.c = [ y.e = 0 ];
  1690                  return y;
  1691              }
  1692  
  1693              // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
  1694              // for finite x and y.
  1695              return normalise( y, xc, ye );
  1696          };
  1697  
  1698  
  1699          /*
  1700           *   n % 0 =  N
  1701           *   n % N =  N
  1702           *   n % I =  n
  1703           *   0 % n =  0
  1704           *  -0 % n = -0
  1705           *   0 % 0 =  N
  1706           *   0 % N =  N
  1707           *   0 % I =  0
  1708           *   N % n =  N
  1709           *   N % 0 =  N
  1710           *   N % N =  N
  1711           *   N % I =  N
  1712           *   I % n =  N
  1713           *   I % 0 =  N
  1714           *   I % N =  N
  1715           *   I % I =  N
  1716           *
  1717           * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
  1718           * BigNumber(y, b). The result depends on the value of MODULO_MODE.
  1719           */
  1720          P.modulo = P.mod = function ( y, b ) {
  1721              var q, s,
  1722                  x = this;
  1723  
  1724              id = 11;
  1725              y = new BigNumber( y, b );
  1726  
  1727              // Return NaN if x is Infinity or NaN, or y is NaN or zero.
  1728              if ( !x.c || !y.s || y.c && !y.c[0] ) {
  1729                  return new BigNumber(NaN);
  1730  
  1731              // Return x if y is Infinity or x is zero.
  1732              } else if ( !y.c || x.c && !x.c[0] ) {
  1733                  return new BigNumber(x);
  1734              }
  1735  
  1736              if ( MODULO_MODE == 9 ) {
  1737  
  1738                  // Euclidian division: q = sign(y) * floor(x / abs(y))
  1739                  // r = x - qy    where  0 <= r < abs(y)
  1740                  s = y.s;
  1741                  y.s = 1;
  1742                  q = div( x, y, 0, 3 );
  1743                  y.s = s;
  1744                  q.s *= s;
  1745              } else {
  1746                  q = div( x, y, 0, MODULO_MODE );
  1747              }
  1748  
  1749              return x.minus( q.times(y) );
  1750          };
  1751  
  1752  
  1753          /*
  1754           * Return a new BigNumber whose value is the value of this BigNumber negated,
  1755           * i.e. multiplied by -1.
  1756           */
  1757          P.negated = P.neg = function () {
  1758              var x = new BigNumber(this);
  1759              x.s = -x.s || null;
  1760              return x;
  1761          };
  1762  
  1763  
  1764          /*
  1765           *  n + 0 = n
  1766           *  n + N = N
  1767           *  n + I = I
  1768           *  0 + n = n
  1769           *  0 + 0 = 0
  1770           *  0 + N = N
  1771           *  0 + I = I
  1772           *  N + n = N
  1773           *  N + 0 = N
  1774           *  N + N = N
  1775           *  N + I = N
  1776           *  I + n = I
  1777           *  I + 0 = I
  1778           *  I + N = N
  1779           *  I + I = I
  1780           *
  1781           * Return a new BigNumber whose value is the value of this BigNumber plus the value of
  1782           * BigNumber(y, b).
  1783           */
  1784          P.plus = P.add = function ( y, b ) {
  1785              var t,
  1786                  x = this,
  1787                  a = x.s;
  1788  
  1789              id = 12;
  1790              y = new BigNumber( y, b );
  1791              b = y.s;
  1792  
  1793              // Either NaN?
  1794              if ( !a || !b ) return new BigNumber(NaN);
  1795  
  1796              // Signs differ?
  1797               if ( a != b ) {
  1798                  y.s = -b;
  1799                  return x.minus(y);
  1800              }
  1801  
  1802              var xe = x.e / LOG_BASE,
  1803                  ye = y.e / LOG_BASE,
  1804                  xc = x.c,
  1805                  yc = y.c;
  1806  
  1807              if ( !xe || !ye ) {
  1808  
  1809                  // Return ±Infinity if either ±Infinity.
  1810                  if ( !xc || !yc ) return new BigNumber( a / 0 );
  1811  
  1812                  // Either zero?
  1813                  // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
  1814                  if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
  1815              }
  1816  
  1817              xe = bitFloor(xe);
  1818              ye = bitFloor(ye);
  1819              xc = xc.slice();
  1820  
  1821              // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
  1822              if ( a = xe - ye ) {
  1823                  if ( a > 0 ) {
  1824                      ye = xe;
  1825                      t = yc;
  1826                  } else {
  1827                      a = -a;
  1828                      t = xc;
  1829                  }
  1830  
  1831                  t.reverse();
  1832                  for ( ; a--; t.push(0) );
  1833                  t.reverse();
  1834              }
  1835  
  1836              a = xc.length;
  1837              b = yc.length;
  1838  
  1839              // Point xc to the longer array, and b to the shorter length.
  1840              if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
  1841  
  1842              // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
  1843              for ( a = 0; b; ) {
  1844                  a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
  1845                  xc[b] %= BASE;
  1846              }
  1847  
  1848              if (a) {
  1849                  xc.unshift(a);
  1850                  ++ye;
  1851              }
  1852  
  1853              // No need to check for zero, as +x + +y != 0 && -x + -y != 0
  1854              // ye = MAX_EXP + 1 possible
  1855              return normalise( y, xc, ye );
  1856          };
  1857  
  1858  
  1859          /*
  1860           * Return the number of significant digits of the value of this BigNumber.
  1861           *
  1862           * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
  1863           */
  1864          P.precision = P.sd = function (z) {
  1865              var n, v,
  1866                  x = this,
  1867                  c = x.c;
  1868  
  1869              // 'precision() argument not a boolean or binary digit: {z}'
  1870              if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
  1871                  if (ERRORS) raise( 13, 'argument' + notBool, z );
  1872                  if ( z != !!z ) z = null;
  1873              }
  1874  
  1875              if ( !c ) return null;
  1876              v = c.length - 1;
  1877              n = v * LOG_BASE + 1;
  1878  
  1879              if ( v = c[v] ) {
  1880  
  1881                  // Subtract the number of trailing zeros of the last element.
  1882                  for ( ; v % 10 == 0; v /= 10, n-- );
  1883  
  1884                  // Add the number of digits of the first element.
  1885                  for ( v = c[0]; v >= 10; v /= 10, n++ );
  1886              }
  1887  
  1888              if ( z && x.e + 1 > n ) n = x.e + 1;
  1889  
  1890              return n;
  1891          };
  1892  
  1893  
  1894          /*
  1895           * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
  1896           * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
  1897           * omitted.
  1898           *
  1899           * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  1900           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  1901           *
  1902           * 'round() decimal places out of range: {dp}'
  1903           * 'round() decimal places not an integer: {dp}'
  1904           * 'round() rounding mode not an integer: {rm}'
  1905           * 'round() rounding mode out of range: {rm}'
  1906           */
  1907          P.round = function ( dp, rm ) {
  1908              var n = new BigNumber(this);
  1909  
  1910              if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
  1911                  round( n, ~~dp + this.e + 1, rm == null ||
  1912                    !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
  1913              }
  1914  
  1915              return n;
  1916          };
  1917  
  1918  
  1919          /*
  1920           * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
  1921           * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
  1922           *
  1923           * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
  1924           *
  1925           * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
  1926           * otherwise.
  1927           *
  1928           * 'shift() argument not an integer: {k}'
  1929           * 'shift() argument out of range: {k}'
  1930           */
  1931          P.shift = function (k) {
  1932              var n = this;
  1933              return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
  1934  
  1935                // k < 1e+21, or truncate(k) will produce exponential notation.
  1936                ? n.times( '1e' + truncate(k) )
  1937                : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
  1938                  ? n.s * ( k < 0 ? 0 : 1 / 0 )
  1939                  : n );
  1940          };
  1941  
  1942  
  1943          /*
  1944           *  sqrt(-n) =  N
  1945           *  sqrt( N) =  N
  1946           *  sqrt(-I) =  N
  1947           *  sqrt( I) =  I
  1948           *  sqrt( 0) =  0
  1949           *  sqrt(-0) = -0
  1950           *
  1951           * Return a new BigNumber whose value is the square root of the value of this BigNumber,
  1952           * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
  1953           */
  1954          P.squareRoot = P.sqrt = function () {
  1955              var m, n, r, rep, t,
  1956                  x = this,
  1957                  c = x.c,
  1958                  s = x.s,
  1959                  e = x.e,
  1960                  dp = DECIMAL_PLACES + 4,
  1961                  half = new BigNumber('0.5');
  1962  
  1963              // Negative/NaN/Infinity/zero?
  1964              if ( s !== 1 || !c || !c[0] ) {
  1965                  return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
  1966              }
  1967  
  1968              // Initial estimate.
  1969              s = Math.sqrt( +x );
  1970  
  1971              // Math.sqrt underflow/overflow?
  1972              // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
  1973              if ( s == 0 || s == 1 / 0 ) {
  1974                  n = coeffToString(c);
  1975                  if ( ( n.length + e ) % 2 == 0 ) n += '0';
  1976                  s = Math.sqrt(n);
  1977                  e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
  1978  
  1979                  if ( s == 1 / 0 ) {
  1980                      n = '1e' + e;
  1981                  } else {
  1982                      n = s.toExponential();
  1983                      n = n.slice( 0, n.indexOf('e') + 1 ) + e;
  1984                  }
  1985  
  1986                  r = new BigNumber(n);
  1987              } else {
  1988                  r = new BigNumber( s + '' );
  1989              }
  1990  
  1991              // Check for zero.
  1992              // r could be zero if MIN_EXP is changed after the this value was created.
  1993              // This would cause a division by zero (x/t) and hence Infinity below, which would cause
  1994              // coeffToString to throw.
  1995              if ( r.c[0] ) {
  1996                  e = r.e;
  1997                  s = e + dp;
  1998                  if ( s < 3 ) s = 0;
  1999  
  2000                  // Newton-Raphson iteration.
  2001                  for ( ; ; ) {
  2002                      t = r;
  2003                      r = half.times( t.plus( div( x, t, dp, 1 ) ) );
  2004  
  2005                      if ( coeffToString( t.c   ).slice( 0, s ) === ( n =
  2006                           coeffToString( r.c ) ).slice( 0, s ) ) {
  2007  
  2008                          // The exponent of r may here be one less than the final result exponent,
  2009                          // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
  2010                          // are indexed correctly.
  2011                          if ( r.e < e ) --s;
  2012                          n = n.slice( s - 3, s + 1 );
  2013  
  2014                          // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
  2015                          // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
  2016                          // iteration.
  2017                          if ( n == '9999' || !rep && n == '4999' ) {
  2018  
  2019                              // On the first iteration only, check to see if rounding up gives the
  2020                              // exact result as the nines may infinitely repeat.
  2021                              if ( !rep ) {
  2022                                  round( t, t.e + DECIMAL_PLACES + 2, 0 );
  2023  
  2024                                  if ( t.times(t).eq(x) ) {
  2025                                      r = t;
  2026                                      break;
  2027                                  }
  2028                              }
  2029  
  2030                              dp += 4;
  2031                              s += 4;
  2032                              rep = 1;
  2033                          } else {
  2034  
  2035                              // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
  2036                              // result. If not, then there are further digits and m will be truthy.
  2037                              if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
  2038  
  2039                                  // Truncate to the first rounding digit.
  2040                                  round( r, r.e + DECIMAL_PLACES + 2, 1 );
  2041                                  m = !r.times(r).eq(x);
  2042                              }
  2043  
  2044                              break;
  2045                          }
  2046                      }
  2047                  }
  2048              }
  2049  
  2050              return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
  2051          };
  2052  
  2053  
  2054          /*
  2055           *  n * 0 = 0
  2056           *  n * N = N
  2057           *  n * I = I
  2058           *  0 * n = 0
  2059           *  0 * 0 = 0
  2060           *  0 * N = N
  2061           *  0 * I = N
  2062           *  N * n = N
  2063           *  N * 0 = N
  2064           *  N * N = N
  2065           *  N * I = N
  2066           *  I * n = I
  2067           *  I * 0 = N
  2068           *  I * N = N
  2069           *  I * I = I
  2070           *
  2071           * Return a new BigNumber whose value is the value of this BigNumber times the value of
  2072           * BigNumber(y, b).
  2073           */
  2074          P.times = P.mul = function ( y, b ) {
  2075              var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
  2076                  base, sqrtBase,
  2077                  x = this,
  2078                  xc = x.c,
  2079                  yc = ( id = 17, y = new BigNumber( y, b ) ).c;
  2080  
  2081              // Either NaN, ±Infinity or ±0?
  2082              if ( !xc || !yc || !xc[0] || !yc[0] ) {
  2083  
  2084                  // Return NaN if either is NaN, or one is 0 and the other is Infinity.
  2085                  if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
  2086                      y.c = y.e = y.s = null;
  2087                  } else {
  2088                      y.s *= x.s;
  2089  
  2090                      // Return ±Infinity if either is ±Infinity.
  2091                      if ( !xc || !yc ) {
  2092                          y.c = y.e = null;
  2093  
  2094                      // Return ±0 if either is ±0.
  2095                      } else {
  2096                          y.c = [0];
  2097                          y.e = 0;
  2098                      }
  2099                  }
  2100  
  2101                  return y;
  2102              }
  2103  
  2104              e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
  2105              y.s *= x.s;
  2106              xcL = xc.length;
  2107              ycL = yc.length;
  2108  
  2109              // Ensure xc points to longer array and xcL to its length.
  2110              if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
  2111  
  2112              // Initialise the result array with zeros.
  2113              for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
  2114  
  2115              base = BASE;
  2116              sqrtBase = SQRT_BASE;
  2117  
  2118              for ( i = ycL; --i >= 0; ) {
  2119                  c = 0;
  2120                  ylo = yc[i] % sqrtBase;
  2121                  yhi = yc[i] / sqrtBase | 0;
  2122  
  2123                  for ( k = xcL, j = i + k; j > i; ) {
  2124                      xlo = xc[--k] % sqrtBase;
  2125                      xhi = xc[k] / sqrtBase | 0;
  2126                      m = yhi * xlo + xhi * ylo;
  2127                      xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
  2128                      c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
  2129                      zc[j--] = xlo % base;
  2130                  }
  2131  
  2132                  zc[j] = c;
  2133              }
  2134  
  2135              if (c) {
  2136                  ++e;
  2137              } else {
  2138                  zc.shift();
  2139              }
  2140  
  2141              return normalise( y, zc, e );
  2142          };
  2143  
  2144  
  2145          /*
  2146           * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
  2147           * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
  2148           *
  2149           * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
  2150           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2151           *
  2152           * 'toDigits() precision out of range: {sd}'
  2153           * 'toDigits() precision not an integer: {sd}'
  2154           * 'toDigits() rounding mode not an integer: {rm}'
  2155           * 'toDigits() rounding mode out of range: {rm}'
  2156           */
  2157          P.toDigits = function ( sd, rm ) {
  2158              var n = new BigNumber(this);
  2159              sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
  2160              rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
  2161              return sd ? round( n, sd, rm ) : n;
  2162          };
  2163  
  2164  
  2165          /*
  2166           * Return a string representing the value of this BigNumber in exponential notation and
  2167           * rounded using ROUNDING_MODE to dp fixed decimal places.
  2168           *
  2169           * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  2170           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2171           *
  2172           * 'toExponential() decimal places not an integer: {dp}'
  2173           * 'toExponential() decimal places out of range: {dp}'
  2174           * 'toExponential() rounding mode not an integer: {rm}'
  2175           * 'toExponential() rounding mode out of range: {rm}'
  2176           */
  2177          P.toExponential = function ( dp, rm ) {
  2178              return format( this,
  2179                dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
  2180          };
  2181  
  2182  
  2183          /*
  2184           * Return a string representing the value of this BigNumber in fixed-point notation rounding
  2185           * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
  2186           *
  2187           * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
  2188           * but e.g. (-0.00001).toFixed(0) is '-0'.
  2189           *
  2190           * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  2191           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2192           *
  2193           * 'toFixed() decimal places not an integer: {dp}'
  2194           * 'toFixed() decimal places out of range: {dp}'
  2195           * 'toFixed() rounding mode not an integer: {rm}'
  2196           * 'toFixed() rounding mode out of range: {rm}'
  2197           */
  2198          P.toFixed = function ( dp, rm ) {
  2199              return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
  2200                ? ~~dp + this.e + 1 : null, rm, 20 );
  2201          };
  2202  
  2203  
  2204          /*
  2205           * Return a string representing the value of this BigNumber in fixed-point notation rounded
  2206           * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
  2207           * of the FORMAT object (see BigNumber.config).
  2208           *
  2209           * FORMAT = {
  2210           *      decimalSeparator : '.',
  2211           *      groupSeparator : ',',
  2212           *      groupSize : 3,
  2213           *      secondaryGroupSize : 0,
  2214           *      fractionGroupSeparator : '\xA0',    // non-breaking space
  2215           *      fractionGroupSize : 0
  2216           * };
  2217           *
  2218           * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
  2219           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2220           *
  2221           * 'toFormat() decimal places not an integer: {dp}'
  2222           * 'toFormat() decimal places out of range: {dp}'
  2223           * 'toFormat() rounding mode not an integer: {rm}'
  2224           * 'toFormat() rounding mode out of range: {rm}'
  2225           */
  2226          P.toFormat = function ( dp, rm ) {
  2227              var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
  2228                ? ~~dp + this.e + 1 : null, rm, 21 );
  2229  
  2230              if ( this.c ) {
  2231                  var i,
  2232                      arr = str.split('.'),
  2233                      g1 = +FORMAT.groupSize,
  2234                      g2 = +FORMAT.secondaryGroupSize,
  2235                      groupSeparator = FORMAT.groupSeparator,
  2236                      intPart = arr[0],
  2237                      fractionPart = arr[1],
  2238                      isNeg = this.s < 0,
  2239                      intDigits = isNeg ? intPart.slice(1) : intPart,
  2240                      len = intDigits.length;
  2241  
  2242                  if (g2) i = g1, g1 = g2, g2 = i, len -= i;
  2243  
  2244                  if ( g1 > 0 && len > 0 ) {
  2245                      i = len % g1 || g1;
  2246                      intPart = intDigits.substr( 0, i );
  2247  
  2248                      for ( ; i < len; i += g1 ) {
  2249                          intPart += groupSeparator + intDigits.substr( i, g1 );
  2250                      }
  2251  
  2252                      if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
  2253                      if (isNeg) intPart = '-' + intPart;
  2254                  }
  2255  
  2256                  str = fractionPart
  2257                    ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
  2258                      ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
  2259                        '$&' + FORMAT.fractionGroupSeparator )
  2260                      : fractionPart )
  2261                    : intPart;
  2262              }
  2263  
  2264              return str;
  2265          };
  2266  
  2267  
  2268          /*
  2269           * Return a string array representing the value of this BigNumber as a simple fraction with
  2270           * an integer numerator and an integer denominator. The denominator will be a positive
  2271           * non-zero value less than or equal to the specified maximum denominator. If a maximum
  2272           * denominator is not specified, the denominator will be the lowest value necessary to
  2273           * represent the number exactly.
  2274           *
  2275           * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
  2276           *
  2277           * 'toFraction() max denominator not an integer: {md}'
  2278           * 'toFraction() max denominator out of range: {md}'
  2279           */
  2280          P.toFraction = function (md) {
  2281              var arr, d0, d2, e, exp, n, n0, q, s,
  2282                  k = ERRORS,
  2283                  x = this,
  2284                  xc = x.c,
  2285                  d = new BigNumber(ONE),
  2286                  n1 = d0 = new BigNumber(ONE),
  2287                  d1 = n0 = new BigNumber(ONE);
  2288  
  2289              if ( md != null ) {
  2290                  ERRORS = false;
  2291                  n = new BigNumber(md);
  2292                  ERRORS = k;
  2293  
  2294                  if ( !( k = n.isInt() ) || n.lt(ONE) ) {
  2295  
  2296                      if (ERRORS) {
  2297                          raise( 22,
  2298                            'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
  2299                      }
  2300  
  2301                      // ERRORS is false:
  2302                      // If md is a finite non-integer >= 1, round it to an integer and use it.
  2303                      md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
  2304                  }
  2305              }
  2306  
  2307              if ( !xc ) return x.toString();
  2308              s = coeffToString(xc);
  2309  
  2310              // Determine initial denominator.
  2311              // d is a power of 10 and the minimum max denominator that specifies the value exactly.
  2312              e = d.e = s.length - x.e - 1;
  2313              d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
  2314              md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
  2315  
  2316              exp = MAX_EXP;
  2317              MAX_EXP = 1 / 0;
  2318              n = new BigNumber(s);
  2319  
  2320              // n0 = d1 = 0
  2321              n0.c[0] = 0;
  2322  
  2323              for ( ; ; )  {
  2324                  q = div( n, d, 0, 1 );
  2325                  d2 = d0.plus( q.times(d1) );
  2326                  if ( d2.cmp(md) == 1 ) break;
  2327                  d0 = d1;
  2328                  d1 = d2;
  2329                  n1 = n0.plus( q.times( d2 = n1 ) );
  2330                  n0 = d2;
  2331                  d = n.minus( q.times( d2 = d ) );
  2332                  n = d2;
  2333              }
  2334  
  2335              d2 = div( md.minus(d0), d1, 0, 1 );
  2336              n0 = n0.plus( d2.times(n1) );
  2337              d0 = d0.plus( d2.times(d1) );
  2338              n0.s = n1.s = x.s;
  2339              e *= 2;
  2340  
  2341              // Determine which fraction is closer to x, n0/d0 or n1/d1
  2342              arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
  2343                    div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
  2344                      ? [ n1.toString(), d1.toString() ]
  2345                      : [ n0.toString(), d0.toString() ];
  2346  
  2347              MAX_EXP = exp;
  2348              return arr;
  2349          };
  2350  
  2351  
  2352          /*
  2353           * Return the value of this BigNumber converted to a number primitive.
  2354           */
  2355          P.toNumber = function () {
  2356              var x = this;
  2357  
  2358              // Ensure zero has correct sign.
  2359              return +x || ( x.s ? x.s * 0 : NaN );
  2360          };
  2361  
  2362  
  2363          /*
  2364           * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
  2365           * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
  2366           * If POW_PRECISION is not 0, round to POW_PRECISION using ROUNDING_MODE.
  2367           *
  2368           * n {number} Integer, -9007199254740992 to 9007199254740992 inclusive.
  2369           * (Performs 54 loop iterations for n of 9007199254740992.)
  2370           *
  2371           * 'pow() exponent not an integer: {n}'
  2372           * 'pow() exponent out of range: {n}'
  2373           */
  2374          P.toPower = P.pow = function (n) {
  2375              var k, y,
  2376                  i = mathfloor( n < 0 ? -n : +n ),
  2377                  x = this;
  2378  
  2379              // Pass ±Infinity to Math.pow if exponent is out of range.
  2380              if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
  2381                ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
  2382                  parseFloat(n) != n && !( n = NaN ) ) ) {
  2383                  return new BigNumber( Math.pow( +x, n ) );
  2384              }
  2385  
  2386              // Truncating each coefficient array to a length of k after each multiplication equates
  2387              // to truncating significant digits to POW_PRECISION + [28, 41], i.e. there will be a
  2388              // minimum of 28 guard digits retained. (Using + 1.5 would give [9, 21] guard digits.)
  2389              k = POW_PRECISION ? mathceil( POW_PRECISION / LOG_BASE + 2 ) : 0;
  2390              y = new BigNumber(ONE);
  2391  
  2392              for ( ; ; ) {
  2393  
  2394                  if ( i % 2 ) {
  2395                      y = y.times(x);
  2396                      if ( !y.c ) break;
  2397                      if ( k && y.c.length > k ) y.c.length = k;
  2398                  }
  2399  
  2400                  i = mathfloor( i / 2 );
  2401                  if ( !i ) break;
  2402  
  2403                  x = x.times(x);
  2404                  if ( k && x.c && x.c.length > k ) x.c.length = k;
  2405              }
  2406  
  2407              if ( n < 0 ) y = ONE.div(y);
  2408              return k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
  2409          };
  2410  
  2411  
  2412          /*
  2413           * Return a string representing the value of this BigNumber rounded to sd significant digits
  2414           * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
  2415           * necessary to represent the integer part of the value in fixed-point notation, then use
  2416           * exponential notation.
  2417           *
  2418           * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
  2419           * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
  2420           *
  2421           * 'toPrecision() precision not an integer: {sd}'
  2422           * 'toPrecision() precision out of range: {sd}'
  2423           * 'toPrecision() rounding mode not an integer: {rm}'
  2424           * 'toPrecision() rounding mode out of range: {rm}'
  2425           */
  2426          P.toPrecision = function ( sd, rm ) {
  2427              return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
  2428                ? sd | 0 : null, rm, 24 );
  2429          };
  2430  
  2431  
  2432          /*
  2433           * Return a string representing the value of this BigNumber in base b, or base 10 if b is
  2434           * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
  2435           * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
  2436           * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
  2437           * TO_EXP_NEG, return exponential notation.
  2438           *
  2439           * [b] {number} Integer, 2 to 64 inclusive.
  2440           *
  2441           * 'toString() base not an integer: {b}'
  2442           * 'toString() base out of range: {b}'
  2443           */
  2444          P.toString = function (b) {
  2445              var str,
  2446                  n = this,
  2447                  s = n.s,
  2448                  e = n.e;
  2449  
  2450              // Infinity or NaN?
  2451              if ( e === null ) {
  2452  
  2453                  if (s) {
  2454                      str = 'Infinity';
  2455                      if ( s < 0 ) str = '-' + str;
  2456                  } else {
  2457                      str = 'NaN';
  2458                  }
  2459              } else {
  2460                  str = coeffToString( n.c );
  2461  
  2462                  if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
  2463                      str = e <= TO_EXP_NEG || e >= TO_EXP_POS
  2464                        ? toExponential( str, e )
  2465                        : toFixedPoint( str, e );
  2466                  } else {
  2467                      str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
  2468                  }
  2469  
  2470                  if ( s < 0 && n.c[0] ) str = '-' + str;
  2471              }
  2472  
  2473              return str;
  2474          };
  2475  
  2476  
  2477          /*
  2478           * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
  2479           * number.
  2480           */
  2481          P.truncated = P.trunc = function () {
  2482              return round( new BigNumber(this), this.e + 1, 1 );
  2483          };
  2484  
  2485  
  2486  
  2487          /*
  2488           * Return as toString, but do not accept a base argument.
  2489           */
  2490          P.valueOf = P.toJSON = function () {
  2491              return this.toString();
  2492          };
  2493  
  2494  
  2495          // Aliases for BigDecimal methods.
  2496          //P.add = P.plus;         // P.add included above
  2497          //P.subtract = P.minus;   // P.sub included above
  2498          //P.multiply = P.times;   // P.mul included above
  2499          //P.divide = P.div;
  2500          //P.remainder = P.mod;
  2501          //P.compareTo = P.cmp;
  2502          //P.negate = P.neg;
  2503  
  2504  
  2505          if ( configObj != null ) BigNumber.config(configObj);
  2506  
  2507          return BigNumber;
  2508      }
  2509  
  2510  
  2511      // PRIVATE HELPER FUNCTIONS
  2512  
  2513  
  2514      function bitFloor(n) {
  2515          var i = n | 0;
  2516          return n > 0 || n === i ? i : i - 1;
  2517      }
  2518  
  2519  
  2520      // Return a coefficient array as a string of base 10 digits.
  2521      function coeffToString(a) {
  2522          var s, z,
  2523              i = 1,
  2524              j = a.length,
  2525              r = a[0] + '';
  2526  
  2527          for ( ; i < j; ) {
  2528              s = a[i++] + '';
  2529              z = LOG_BASE - s.length;
  2530              for ( ; z--; s = '0' + s );
  2531              r += s;
  2532          }
  2533  
  2534          // Determine trailing zeros.
  2535          for ( j = r.length; r.charCodeAt(--j) === 48; );
  2536          return r.slice( 0, j + 1 || 1 );
  2537      }
  2538  
  2539  
  2540      // Compare the value of BigNumbers x and y.
  2541      function compare( x, y ) {
  2542          var a, b,
  2543              xc = x.c,
  2544              yc = y.c,
  2545              i = x.s,
  2546              j = y.s,
  2547              k = x.e,
  2548              l = y.e;
  2549  
  2550          // Either NaN?
  2551          if ( !i || !j ) return null;
  2552  
  2553          a = xc && !xc[0];
  2554          b = yc && !yc[0];
  2555  
  2556          // Either zero?
  2557          if ( a || b ) return a ? b ? 0 : -j : i;
  2558  
  2559          // Signs differ?
  2560          if ( i != j ) return i;
  2561  
  2562          a = i < 0;
  2563          b = k == l;
  2564  
  2565          // Either Infinity?
  2566          if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
  2567  
  2568          // Compare exponents.
  2569          if ( !b ) return k > l ^ a ? 1 : -1;
  2570  
  2571          j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
  2572  
  2573          // Compare digit by digit.
  2574          for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
  2575  
  2576          // Compare lengths.
  2577          return k == l ? 0 : k > l ^ a ? 1 : -1;
  2578      }
  2579  
  2580  
  2581      /*
  2582       * Return true if n is a valid number in range, otherwise false.
  2583       * Use for argument validation when ERRORS is false.
  2584       * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
  2585       */
  2586      function intValidatorNoErrors( n, min, max ) {
  2587          return ( n = truncate(n) ) >= min && n <= max;
  2588      }
  2589  
  2590  
  2591      function isArray(obj) {
  2592          return Object.prototype.toString.call(obj) == '[object Array]';
  2593      }
  2594  
  2595  
  2596      /*
  2597       * Convert string of baseIn to an array of numbers of baseOut.
  2598       * Eg. convertBase('255', 10, 16) returns [15, 15].
  2599       * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
  2600       */
  2601      function toBaseOut( str, baseIn, baseOut ) {
  2602          var j,
  2603              arr = [0],
  2604              arrL,
  2605              i = 0,
  2606              len = str.length;
  2607  
  2608          for ( ; i < len; ) {
  2609              for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
  2610              arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
  2611  
  2612              for ( ; j < arr.length; j++ ) {
  2613  
  2614                  if ( arr[j] > baseOut - 1 ) {
  2615                      if ( arr[j + 1] == null ) arr[j + 1] = 0;
  2616                      arr[j + 1] += arr[j] / baseOut | 0;
  2617                      arr[j] %= baseOut;
  2618                  }
  2619              }
  2620          }
  2621  
  2622          return arr.reverse();
  2623      }
  2624  
  2625  
  2626      function toExponential( str, e ) {
  2627          return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
  2628            ( e < 0 ? 'e' : 'e+' ) + e;
  2629      }
  2630  
  2631  
  2632      function toFixedPoint( str, e ) {
  2633          var len, z;
  2634  
  2635          // Negative exponent?
  2636          if ( e < 0 ) {
  2637  
  2638              // Prepend zeros.
  2639              for ( z = '0.'; ++e; z += '0' );
  2640              str = z + str;
  2641  
  2642          // Positive exponent
  2643          } else {
  2644              len = str.length;
  2645  
  2646              // Append zeros.
  2647              if ( ++e > len ) {
  2648                  for ( z = '0', e -= len; --e; z += '0' );
  2649                  str += z;
  2650              } else if ( e < len ) {
  2651                  str = str.slice( 0, e ) + '.' + str.slice(e);
  2652              }
  2653          }
  2654  
  2655          return str;
  2656      }
  2657  
  2658  
  2659      function truncate(n) {
  2660          n = parseFloat(n);
  2661          return n < 0 ? mathceil(n) : mathfloor(n);
  2662      }
  2663  
  2664  
  2665      // EXPORT
  2666  
  2667  
  2668      BigNumber = another();
  2669  
  2670      // AMD.
  2671      if ( typeof define == 'function' && define.amd ) {
  2672          define( function () { return BigNumber; } );
  2673  
  2674      // Node and other environments that support module.exports.
  2675      } else if ( typeof module != 'undefined' && module.exports ) {
  2676          module.exports = BigNumber;
  2677          if ( !crypto ) try { crypto = require('crypto'); } catch (e) {}
  2678  
  2679      // Browser.
  2680      } else {
  2681          global.BigNumber = BigNumber;
  2682      }
  2683  })(this);