Source: node_modules/bson/lib/bson/decimal128.js

  1. 'use strict';
  2. let Long = require('./long');
  3. var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  4. var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  5. var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  6. var EXPONENT_MAX = 6111;
  7. var EXPONENT_MIN = -6176;
  8. var EXPONENT_BIAS = 6176;
  9. var MAX_DIGITS = 34;
  10. // Nan value bits as 32 bit values (due to lack of longs)
  11. var NAN_BUFFER = [
  12. 0x7c,
  13. 0x00,
  14. 0x00,
  15. 0x00,
  16. 0x00,
  17. 0x00,
  18. 0x00,
  19. 0x00,
  20. 0x00,
  21. 0x00,
  22. 0x00,
  23. 0x00,
  24. 0x00,
  25. 0x00,
  26. 0x00,
  27. 0x00
  28. ].reverse();
  29. // Infinity value bits 32 bit values (due to lack of longs)
  30. var INF_NEGATIVE_BUFFER = [
  31. 0xf8,
  32. 0x00,
  33. 0x00,
  34. 0x00,
  35. 0x00,
  36. 0x00,
  37. 0x00,
  38. 0x00,
  39. 0x00,
  40. 0x00,
  41. 0x00,
  42. 0x00,
  43. 0x00,
  44. 0x00,
  45. 0x00,
  46. 0x00
  47. ].reverse();
  48. var INF_POSITIVE_BUFFER = [
  49. 0x78,
  50. 0x00,
  51. 0x00,
  52. 0x00,
  53. 0x00,
  54. 0x00,
  55. 0x00,
  56. 0x00,
  57. 0x00,
  58. 0x00,
  59. 0x00,
  60. 0x00,
  61. 0x00,
  62. 0x00,
  63. 0x00,
  64. 0x00
  65. ].reverse();
  66. var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
  67. // Detect if the value is a digit
  68. var isDigit = function(value) {
  69. return !isNaN(parseInt(value, 10));
  70. };
  71. // Divide two uint128 values
  72. var divideu128 = function(value) {
  73. var DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
  74. var _rem = Long.fromNumber(0);
  75. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  76. return { quotient: value, rem: _rem };
  77. }
  78. for (let i = 0; i <= 3; i++) {
  79. // Adjust remainder to match value of next dividend
  80. _rem = _rem.shiftLeft(32);
  81. // Add the divided to _rem
  82. _rem = _rem.add(new Long(value.parts[i], 0));
  83. value.parts[i] = _rem.div(DIVISOR).low_;
  84. _rem = _rem.modulo(DIVISOR);
  85. }
  86. return { quotient: value, rem: _rem };
  87. };
  88. // Multiply two Long values and return the 128 bit value
  89. var multiply64x2 = function(left, right) {
  90. if (!left && !right) {
  91. return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
  92. }
  93. var leftHigh = left.shiftRightUnsigned(32);
  94. var leftLow = new Long(left.getLowBits(), 0);
  95. var rightHigh = right.shiftRightUnsigned(32);
  96. var rightLow = new Long(right.getLowBits(), 0);
  97. var productHigh = leftHigh.multiply(rightHigh);
  98. var productMid = leftHigh.multiply(rightLow);
  99. var productMid2 = leftLow.multiply(rightHigh);
  100. var productLow = leftLow.multiply(rightLow);
  101. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  102. productMid = new Long(productMid.getLowBits(), 0)
  103. .add(productMid2)
  104. .add(productLow.shiftRightUnsigned(32));
  105. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  106. productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
  107. // Return the 128 bit result
  108. return { high: productHigh, low: productLow };
  109. };
  110. var lessThan = function(left, right) {
  111. // Make values unsigned
  112. var uhleft = left.high_ >>> 0;
  113. var uhright = right.high_ >>> 0;
  114. // Compare high bits first
  115. if (uhleft < uhright) {
  116. return true;
  117. } else if (uhleft === uhright) {
  118. var ulleft = left.low_ >>> 0;
  119. var ulright = right.low_ >>> 0;
  120. if (ulleft < ulright) return true;
  121. }
  122. return false;
  123. };
  124. var invalidErr = function(string, message) {
  125. throw new TypeError('"${string}" not a valid Decimal128 string - ' + message);
  126. };
  127. /**
  128. * A class representation of the BSON Decimal128 type.
  129. *
  130. * @class
  131. * @param {Buffer} bytes a buffer containing the raw Decimal128 bytes.
  132. * @return {Double}
  133. */
  134. function Decimal128(bytes) {
  135. this._bsontype = 'Decimal128';
  136. this.bytes = bytes;
  137. }
  138. /**
  139. * Create a Decimal128 instance from a string representation
  140. *
  141. * @method
  142. * @param {string} string a numeric string representation.
  143. * @return {Decimal128} returns a Decimal128 instance.
  144. */
  145. Decimal128.fromString = function(string) {
  146. // Parse state tracking
  147. var isNegative = false;
  148. var sawRadix = false;
  149. var foundNonZero = false;
  150. // Total number of significant digits (no leading or trailing zero)
  151. var significantDigits = 0;
  152. // Total number of significand digits read
  153. var nDigitsRead = 0;
  154. // Total number of digits (no leading zeros)
  155. var nDigits = 0;
  156. // The number of the digits after radix
  157. var radixPosition = 0;
  158. // The index of the first non-zero in *str*
  159. var firstNonZero = 0;
  160. // Digits Array
  161. var digits = [0];
  162. // The number of digits in digits
  163. var nDigitsStored = 0;
  164. // Insertion pointer for digits
  165. var digitsInsert = 0;
  166. // The index of the first non-zero digit
  167. var firstDigit = 0;
  168. // The index of the last digit
  169. var lastDigit = 0;
  170. // Exponent
  171. var exponent = 0;
  172. // loop index over array
  173. var i = 0;
  174. // The high 17 digits of the significand
  175. var significandHigh = [0, 0];
  176. // The low 17 digits of the significand
  177. var significandLow = [0, 0];
  178. // The biased exponent
  179. var biasedExponent = 0;
  180. // Read index
  181. var index = 0;
  182. // Naively prevent against REDOS attacks.
  183. // TODO: implementing a custom parsing for this, or refactoring the regex would yield
  184. // further gains.
  185. if (string.length >= 7000) {
  186. throw new TypeError('' + string + ' not a valid Decimal128 string');
  187. }
  188. // Results
  189. var stringMatch = string.match(PARSE_STRING_REGEXP);
  190. var infMatch = string.match(PARSE_INF_REGEXP);
  191. var nanMatch = string.match(PARSE_NAN_REGEXP);
  192. // Validate the string
  193. if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) {
  194. throw new TypeError('' + string + ' not a valid Decimal128 string');
  195. }
  196. if (stringMatch) {
  197. // full_match = stringMatch[0]
  198. // sign = stringMatch[1]
  199. var unsignedNumber = stringMatch[2];
  200. // stringMatch[3] is undefined if a whole number (ex "1", 12")
  201. // but defined if a number w/ decimal in it (ex "1.0, 12.2")
  202. var e = stringMatch[4];
  203. var expSign = stringMatch[5];
  204. var expNumber = stringMatch[6];
  205. // they provided e, but didn't give an exponent number. for ex "1e"
  206. if (e && expNumber === undefined) invalidErr(string, 'missing exponent power');
  207. // they provided e, but didn't give a number before it. for ex "e1"
  208. if (e && unsignedNumber === undefined) invalidErr(string, 'missing exponent base');
  209. if (e === undefined && (expSign || expNumber)) {
  210. invalidErr(string, 'missing e before exponent');
  211. }
  212. }
  213. // Get the negative or positive sign
  214. if (string[index] === '+' || string[index] === '-') {
  215. isNegative = string[index++] === '-';
  216. }
  217. // Check if user passed Infinity or NaN
  218. if (!isDigit(string[index]) && string[index] !== '.') {
  219. if (string[index] === 'i' || string[index] === 'I') {
  220. return new Decimal128(new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER));
  221. } else if (string[index] === 'N') {
  222. return new Decimal128(new Buffer(NAN_BUFFER));
  223. }
  224. }
  225. // Read all the digits
  226. while (isDigit(string[index]) || string[index] === '.') {
  227. if (string[index] === '.') {
  228. if (sawRadix) invalidErr(string, 'contains multiple periods');
  229. sawRadix = true;
  230. index = index + 1;
  231. continue;
  232. }
  233. if (nDigitsStored < 34) {
  234. if (string[index] !== '0' || foundNonZero) {
  235. if (!foundNonZero) {
  236. firstNonZero = nDigitsRead;
  237. }
  238. foundNonZero = true;
  239. // Only store 34 digits
  240. digits[digitsInsert++] = parseInt(string[index], 10);
  241. nDigitsStored = nDigitsStored + 1;
  242. }
  243. }
  244. if (foundNonZero) nDigits = nDigits + 1;
  245. if (sawRadix) radixPosition = radixPosition + 1;
  246. nDigitsRead = nDigitsRead + 1;
  247. index = index + 1;
  248. }
  249. if (sawRadix && !nDigitsRead) throw new TypeError('' + string + ' not a valid Decimal128 string');
  250. // Read exponent if exists
  251. if (string[index] === 'e' || string[index] === 'E') {
  252. // Read exponent digits
  253. var match = string.substr(++index).match(EXPONENT_REGEX);
  254. // No digits read
  255. if (!match || !match[2]) return new Decimal128(new Buffer(NAN_BUFFER));
  256. // Get exponent
  257. exponent = parseInt(match[0], 10);
  258. // Adjust the index
  259. index = index + match[0].length;
  260. }
  261. // Return not a number
  262. if (string[index]) return new Decimal128(new Buffer(NAN_BUFFER));
  263. // Done reading input
  264. // Find first non-zero digit in digits
  265. firstDigit = 0;
  266. if (!nDigitsStored) {
  267. firstDigit = 0;
  268. lastDigit = 0;
  269. digits[0] = 0;
  270. nDigits = 1;
  271. nDigitsStored = 1;
  272. significantDigits = 0;
  273. } else {
  274. lastDigit = nDigitsStored - 1;
  275. significantDigits = nDigits;
  276. if (significantDigits !== 1) {
  277. while (string[firstNonZero + significantDigits - 1] === '0') {
  278. significantDigits = significantDigits - 1;
  279. }
  280. }
  281. }
  282. // Normalization of exponent
  283. // Correct exponent based on radix position, and shift significand as needed
  284. // to represent user input
  285. // Overflow prevention
  286. if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) {
  287. exponent = EXPONENT_MIN;
  288. } else {
  289. exponent = exponent - radixPosition;
  290. }
  291. // Attempt to normalize the exponent
  292. while (exponent > EXPONENT_MAX) {
  293. // Shift exponent to significand and decrease
  294. lastDigit = lastDigit + 1;
  295. if (lastDigit - firstDigit > MAX_DIGITS) {
  296. // Check if we have a zero then just hard clamp, otherwise fail
  297. var digitsString = digits.join('');
  298. if (digitsString.match(/^0+$/)) {
  299. exponent = EXPONENT_MAX;
  300. break;
  301. }
  302. invalidErr(string, 'overflow');
  303. }
  304. exponent = exponent - 1;
  305. }
  306. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  307. // Shift last digit. can only do this if < significant digits than # stored.
  308. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  309. exponent = EXPONENT_MIN;
  310. significantDigits = 0;
  311. break;
  312. }
  313. if (nDigitsStored < nDigits) {
  314. // adjust to match digits not stored
  315. nDigits = nDigits - 1;
  316. } else {
  317. // adjust to round
  318. lastDigit = lastDigit - 1;
  319. }
  320. if (exponent < EXPONENT_MAX) {
  321. exponent = exponent + 1;
  322. } else {
  323. // Check if we have a zero then just hard clamp, otherwise fail
  324. digitsString = digits.join('');
  325. if (digitsString.match(/^0+$/)) {
  326. exponent = EXPONENT_MAX;
  327. break;
  328. }
  329. invalidErr(string, 'overflow');
  330. }
  331. }
  332. // Round
  333. // We've normalized the exponent, but might still need to round.
  334. if (lastDigit - firstDigit + 1 < significantDigits) {
  335. var endOfString = nDigitsRead;
  336. // If we have seen a radix point, 'string' is 1 longer than we have
  337. // documented with ndigits_read, so inc the position of the first nonzero
  338. // digit and the position that digits are read to.
  339. if (sawRadix) {
  340. firstNonZero = firstNonZero + 1;
  341. endOfString = endOfString + 1;
  342. }
  343. // if negative, we need to increment again to account for - sign at start.
  344. if (isNegative) {
  345. firstNonZero = firstNonZero + 1;
  346. endOfString = endOfString + 1;
  347. }
  348. var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10);
  349. var roundBit = 0;
  350. if (roundDigit >= 5) {
  351. roundBit = 1;
  352. if (roundDigit === 5) {
  353. roundBit = digits[lastDigit] % 2 === 1;
  354. for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  355. if (parseInt(string[i], 10)) {
  356. roundBit = 1;
  357. break;
  358. }
  359. }
  360. }
  361. }
  362. if (roundBit) {
  363. var dIdx = lastDigit;
  364. for (; dIdx >= 0; dIdx--) {
  365. if (++digits[dIdx] > 9) {
  366. digits[dIdx] = 0;
  367. // overflowed most significant digit
  368. if (dIdx === 0) {
  369. if (exponent < EXPONENT_MAX) {
  370. exponent = exponent + 1;
  371. digits[dIdx] = 1;
  372. } else {
  373. return new Decimal128(
  374. new Buffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)
  375. );
  376. }
  377. }
  378. }
  379. }
  380. }
  381. }
  382. // Encode significand
  383. // The high 17 digits of the significand
  384. significandHigh = Long.fromNumber(0);
  385. // The low 17 digits of the significand
  386. significandLow = Long.fromNumber(0);
  387. // read a zero
  388. if (significantDigits === 0) {
  389. significandHigh = Long.fromNumber(0);
  390. significandLow = Long.fromNumber(0);
  391. } else if (lastDigit - firstDigit < 17) {
  392. dIdx = firstDigit;
  393. significandLow = Long.fromNumber(digits[dIdx++]);
  394. significandHigh = new Long(0, 0);
  395. for (; dIdx <= lastDigit; dIdx++) {
  396. significandLow = significandLow.multiply(Long.fromNumber(10));
  397. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  398. }
  399. } else {
  400. dIdx = firstDigit;
  401. significandHigh = Long.fromNumber(digits[dIdx++]);
  402. for (; dIdx <= lastDigit - 17; dIdx++) {
  403. significandHigh = significandHigh.multiply(Long.fromNumber(10));
  404. significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
  405. }
  406. significandLow = Long.fromNumber(digits[dIdx++]);
  407. for (; dIdx <= lastDigit; dIdx++) {
  408. significandLow = significandLow.multiply(Long.fromNumber(10));
  409. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  410. }
  411. }
  412. var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
  413. significand.low = significand.low.add(significandLow);
  414. if (lessThan(significand.low, significandLow)) {
  415. significand.high = significand.high.add(Long.fromNumber(1));
  416. }
  417. // Biased exponent
  418. biasedExponent = exponent + EXPONENT_BIAS;
  419. var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
  420. // Encode combination, exponent, and significand.
  421. if (
  422. significand.high
  423. .shiftRightUnsigned(49)
  424. .and(Long.fromNumber(1))
  425. .equals(Long.fromNumber)
  426. ) {
  427. // Encode '11' into bits 1 to 3
  428. dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
  429. dec.high = dec.high.or(
  430. Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47))
  431. );
  432. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
  433. } else {
  434. dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  435. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
  436. }
  437. dec.low = significand.low;
  438. // Encode sign
  439. if (isNegative) {
  440. dec.high = dec.high.or(Long.fromString('9223372036854775808'));
  441. }
  442. // Encode into a buffer
  443. var buffer = new Buffer(16);
  444. index = 0;
  445. // Encode the low 64 bits of the decimal
  446. // Encode low bits
  447. buffer[index++] = dec.low.low_ & 0xff;
  448. buffer[index++] = (dec.low.low_ >> 8) & 0xff;
  449. buffer[index++] = (dec.low.low_ >> 16) & 0xff;
  450. buffer[index++] = (dec.low.low_ >> 24) & 0xff;
  451. // Encode high bits
  452. buffer[index++] = dec.low.high_ & 0xff;
  453. buffer[index++] = (dec.low.high_ >> 8) & 0xff;
  454. buffer[index++] = (dec.low.high_ >> 16) & 0xff;
  455. buffer[index++] = (dec.low.high_ >> 24) & 0xff;
  456. // Encode the high 64 bits of the decimal
  457. // Encode low bits
  458. buffer[index++] = dec.high.low_ & 0xff;
  459. buffer[index++] = (dec.high.low_ >> 8) & 0xff;
  460. buffer[index++] = (dec.high.low_ >> 16) & 0xff;
  461. buffer[index++] = (dec.high.low_ >> 24) & 0xff;
  462. // Encode high bits
  463. buffer[index++] = dec.high.high_ & 0xff;
  464. buffer[index++] = (dec.high.high_ >> 8) & 0xff;
  465. buffer[index++] = (dec.high.high_ >> 16) & 0xff;
  466. buffer[index++] = (dec.high.high_ >> 24) & 0xff;
  467. // Return the new Decimal128
  468. return new Decimal128(buffer);
  469. };
  470. // Extract least significant 5 bits
  471. var COMBINATION_MASK = 0x1f;
  472. // Extract least significant 14 bits
  473. var EXPONENT_MASK = 0x3fff;
  474. // Value of combination field for Inf
  475. var COMBINATION_INFINITY = 30;
  476. // Value of combination field for NaN
  477. var COMBINATION_NAN = 31;
  478. // Value of combination field for NaN
  479. // var COMBINATION_SNAN = 32;
  480. // decimal128 exponent bias
  481. EXPONENT_BIAS = 6176;
  482. /**
  483. * Create a string representation of the raw Decimal128 value
  484. *
  485. * @method
  486. * @return {string} returns a Decimal128 string representation.
  487. */
  488. Decimal128.prototype.toString = function() {
  489. // Note: bits in this routine are referred to starting at 0,
  490. // from the sign bit, towards the coefficient.
  491. // bits 0 - 31
  492. var high;
  493. // bits 32 - 63
  494. var midh;
  495. // bits 64 - 95
  496. var midl;
  497. // bits 96 - 127
  498. var low;
  499. // bits 1 - 5
  500. var combination;
  501. // decoded biased exponent (14 bits)
  502. var biased_exponent;
  503. // the number of significand digits
  504. var significand_digits = 0;
  505. // the base-10 digits in the significand
  506. var significand = new Array(36);
  507. for (var i = 0; i < significand.length; i++) significand[i] = 0;
  508. // read pointer into significand
  509. var index = 0;
  510. // unbiased exponent
  511. var exponent;
  512. // the exponent if scientific notation is used
  513. var scientific_exponent;
  514. // true if the number is zero
  515. var is_zero = false;
  516. // the most signifcant significand bits (50-46)
  517. var significand_msb;
  518. // temporary storage for significand decoding
  519. var significand128 = { parts: new Array(4) };
  520. // indexing variables
  521. var j, k;
  522. // Output string
  523. var string = [];
  524. // Unpack index
  525. index = 0;
  526. // Buffer reference
  527. var buffer = this.bytes;
  528. // Unpack the low 64bits into a long
  529. low =
  530. buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  531. midl =
  532. buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  533. // Unpack the high 64bits into a long
  534. midh =
  535. buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  536. high =
  537. buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  538. // Unpack index
  539. index = 0;
  540. // Create the state of the decimal
  541. var dec = {
  542. low: new Long(low, midl),
  543. high: new Long(midh, high)
  544. };
  545. if (dec.high.lessThan(Long.ZERO)) {
  546. string.push('-');
  547. }
  548. // Decode combination field and exponent
  549. combination = (high >> 26) & COMBINATION_MASK;
  550. if (combination >> 3 === 3) {
  551. // Check for 'special' values
  552. if (combination === COMBINATION_INFINITY) {
  553. return string.join('') + 'Infinity';
  554. } else if (combination === COMBINATION_NAN) {
  555. return 'NaN';
  556. } else {
  557. biased_exponent = (high >> 15) & EXPONENT_MASK;
  558. significand_msb = 0x08 + ((high >> 14) & 0x01);
  559. }
  560. } else {
  561. significand_msb = (high >> 14) & 0x07;
  562. biased_exponent = (high >> 17) & EXPONENT_MASK;
  563. }
  564. exponent = biased_exponent - EXPONENT_BIAS;
  565. // Create string of significand digits
  566. // Convert the 114-bit binary number represented by
  567. // (significand_high, significand_low) to at most 34 decimal
  568. // digits through modulo and division.
  569. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  570. significand128.parts[1] = midh;
  571. significand128.parts[2] = midl;
  572. significand128.parts[3] = low;
  573. if (
  574. significand128.parts[0] === 0 &&
  575. significand128.parts[1] === 0 &&
  576. significand128.parts[2] === 0 &&
  577. significand128.parts[3] === 0
  578. ) {
  579. is_zero = true;
  580. } else {
  581. for (k = 3; k >= 0; k--) {
  582. var least_digits = 0;
  583. // Peform the divide
  584. var result = divideu128(significand128);
  585. significand128 = result.quotient;
  586. least_digits = result.rem.low_;
  587. // We now have the 9 least significant digits (in base 2).
  588. // Convert and output to string.
  589. if (!least_digits) continue;
  590. for (j = 8; j >= 0; j--) {
  591. // significand[k * 9 + j] = Math.round(least_digits % 10);
  592. significand[k * 9 + j] = least_digits % 10;
  593. // least_digits = Math.round(least_digits / 10);
  594. least_digits = Math.floor(least_digits / 10);
  595. }
  596. }
  597. }
  598. // Output format options:
  599. // Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
  600. // Regular - ddd.ddd
  601. if (is_zero) {
  602. significand_digits = 1;
  603. significand[index] = 0;
  604. } else {
  605. significand_digits = 36;
  606. i = 0;
  607. while (!significand[index]) {
  608. i++;
  609. significand_digits = significand_digits - 1;
  610. index = index + 1;
  611. }
  612. }
  613. scientific_exponent = significand_digits - 1 + exponent;
  614. // The scientific exponent checks are dictated by the string conversion
  615. // specification and are somewhat arbitrary cutoffs.
  616. //
  617. // We must check exponent > 0, because if this is the case, the number
  618. // has trailing zeros. However, we *cannot* output these trailing zeros,
  619. // because doing so would change the precision of the value, and would
  620. // change stored data if the string converted number is round tripped.
  621. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  622. // Scientific format
  623. // if there are too many significant digits, we should just be treating numbers
  624. // as + or - 0 and using the non-scientific exponent (this is for the "invalid
  625. // representation should be treated as 0/-0" spec cases in decimal128-1.json)
  626. if (significand_digits > 34) {
  627. string.push(0);
  628. if (exponent > 0) string.push('E+' + exponent);
  629. else if (exponent < 0) string.push('E' + exponent);
  630. return string.join('');
  631. }
  632. string.push(significand[index++]);
  633. significand_digits = significand_digits - 1;
  634. if (significand_digits) {
  635. string.push('.');
  636. }
  637. for (i = 0; i < significand_digits; i++) {
  638. string.push(significand[index++]);
  639. }
  640. // Exponent
  641. string.push('E');
  642. if (scientific_exponent > 0) {
  643. string.push('+' + scientific_exponent);
  644. } else {
  645. string.push(scientific_exponent);
  646. }
  647. } else {
  648. // Regular format with no decimal place
  649. if (exponent >= 0) {
  650. for (i = 0; i < significand_digits; i++) {
  651. string.push(significand[index++]);
  652. }
  653. } else {
  654. var radix_position = significand_digits + exponent;
  655. // non-zero digits before radix
  656. if (radix_position > 0) {
  657. for (i = 0; i < radix_position; i++) {
  658. string.push(significand[index++]);
  659. }
  660. } else {
  661. string.push('0');
  662. }
  663. string.push('.');
  664. // add leading zeros after radix
  665. while (radix_position++ < 0) {
  666. string.push('0');
  667. }
  668. for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
  669. string.push(significand[index++]);
  670. }
  671. }
  672. }
  673. return string.join('');
  674. };
  675. Decimal128.prototype.toJSON = function() {
  676. return { $numberDecimal: this.toString() };
  677. };
  678. module.exports = Decimal128;
  679. module.exports.Decimal128 = Decimal128;