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

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