bignumber.mjs 77 KB

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