bignumber.js 81 KB

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