fixednumber.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /**
  2. * The **FixedNumber** class permits using values with decimal places,
  3. * using fixed-pont math.
  4. *
  5. * Fixed-point math is still based on integers under-the-hood, but uses an
  6. * internal offset to store fractional components below, and each operation
  7. * corrects for this after each operation.
  8. *
  9. * @_section: api/utils/fixed-point-math:Fixed-Point Maths [about-fixed-point-math]
  10. */
  11. import { getBytes } from "./data.js";
  12. import { assert, assertArgument, assertPrivate } from "./errors.js";
  13. import { getBigInt, getNumber, fromTwos, mask, toBigInt } from "./maths.js";
  14. import { defineProperties } from "./properties.js";
  15. const BN_N1 = BigInt(-1);
  16. const BN_0 = BigInt(0);
  17. const BN_1 = BigInt(1);
  18. const BN_5 = BigInt(5);
  19. const _guard = {};
  20. // Constant to pull zeros from for multipliers
  21. let Zeros = "0000";
  22. while (Zeros.length < 80) {
  23. Zeros += Zeros;
  24. }
  25. // Returns a string "1" followed by decimal "0"s
  26. function getTens(decimals) {
  27. let result = Zeros;
  28. while (result.length < decimals) {
  29. result += result;
  30. }
  31. return BigInt("1" + result.substring(0, decimals));
  32. }
  33. function checkValue(val, format, safeOp) {
  34. const width = BigInt(format.width);
  35. if (format.signed) {
  36. const limit = (BN_1 << (width - BN_1));
  37. assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
  38. operation: safeOp, fault: "overflow", value: val
  39. });
  40. if (val > BN_0) {
  41. val = fromTwos(mask(val, width), width);
  42. }
  43. else {
  44. val = -fromTwos(mask(-val, width), width);
  45. }
  46. }
  47. else {
  48. const limit = (BN_1 << width);
  49. assert(safeOp == null || (val >= 0 && val < limit), "overflow", "NUMERIC_FAULT", {
  50. operation: safeOp, fault: "overflow", value: val
  51. });
  52. val = (((val % limit) + limit) % limit) & (limit - BN_1);
  53. }
  54. return val;
  55. }
  56. function getFormat(value) {
  57. if (typeof (value) === "number") {
  58. value = `fixed128x${value}`;
  59. }
  60. let signed = true;
  61. let width = 128;
  62. let decimals = 18;
  63. if (typeof (value) === "string") {
  64. // Parse the format string
  65. if (value === "fixed") {
  66. // defaults...
  67. }
  68. else if (value === "ufixed") {
  69. signed = false;
  70. }
  71. else {
  72. const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);
  73. assertArgument(match, "invalid fixed format", "format", value);
  74. signed = (match[1] !== "u");
  75. width = parseInt(match[2]);
  76. decimals = parseInt(match[3]);
  77. }
  78. }
  79. else if (value) {
  80. // Extract the values from the object
  81. const v = value;
  82. const check = (key, type, defaultValue) => {
  83. if (v[key] == null) {
  84. return defaultValue;
  85. }
  86. assertArgument(typeof (v[key]) === type, "invalid fixed format (" + key + " not " + type + ")", "format." + key, v[key]);
  87. return v[key];
  88. };
  89. signed = check("signed", "boolean", signed);
  90. width = check("width", "number", width);
  91. decimals = check("decimals", "number", decimals);
  92. }
  93. assertArgument((width % 8) === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width);
  94. assertArgument(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals);
  95. const name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals);
  96. return { signed, width, decimals, name };
  97. }
  98. function toString(val, decimals) {
  99. let negative = "";
  100. if (val < BN_0) {
  101. negative = "-";
  102. val *= BN_N1;
  103. }
  104. let str = val.toString();
  105. // No decimal point for whole values
  106. if (decimals === 0) {
  107. return (negative + str);
  108. }
  109. // Pad out to the whole component (including a whole digit)
  110. while (str.length <= decimals) {
  111. str = Zeros + str;
  112. }
  113. // Insert the decimal point
  114. const index = str.length - decimals;
  115. str = str.substring(0, index) + "." + str.substring(index);
  116. // Trim the whole component (leaving at least one 0)
  117. while (str[0] === "0" && str[1] !== ".") {
  118. str = str.substring(1);
  119. }
  120. // Trim the decimal component (leaving at least one 0)
  121. while (str[str.length - 1] === "0" && str[str.length - 2] !== ".") {
  122. str = str.substring(0, str.length - 1);
  123. }
  124. return (negative + str);
  125. }
  126. /**
  127. * A FixedNumber represents a value over its [[FixedFormat]]
  128. * arithmetic field.
  129. *
  130. * A FixedNumber can be used to perform math, losslessly, on
  131. * values which have decmial places.
  132. *
  133. * A FixedNumber has a fixed bit-width to store values in, and stores all
  134. * values internally by multiplying the value by 10 raised to the power of
  135. * %%decimals%%.
  136. *
  137. * If operations are performed that cause a value to grow too high (close to
  138. * positive infinity) or too low (close to negative infinity), the value
  139. * is said to //overflow//.
  140. *
  141. * For example, an 8-bit signed value, with 0 decimals may only be within
  142. * the range ``-128`` to ``127``; so ``-128 - 1`` will overflow and become
  143. * ``127``. Likewise, ``127 + 1`` will overflow and become ``-127``.
  144. *
  145. * Many operation have a normal and //unsafe// variant. The normal variant
  146. * will throw a [[NumericFaultError]] on any overflow, while the //unsafe//
  147. * variant will silently allow overflow, corrupting its value value.
  148. *
  149. * If operations are performed that cause a value to become too small
  150. * (close to zero), the value loses precison and is said to //underflow//.
  151. *
  152. * For example, an value with 1 decimal place may store a number as small
  153. * as ``0.1``, but the value of ``0.1 / 2`` is ``0.05``, which cannot fit
  154. * into 1 decimal place, so underflow occurs which means precision is lost
  155. * and the value becomes ``0``.
  156. *
  157. * Some operations have a normal and //signalling// variant. The normal
  158. * variant will silently ignore underflow, while the //signalling// variant
  159. * will thow a [[NumericFaultError]] on underflow.
  160. */
  161. export class FixedNumber {
  162. /**
  163. * The specific fixed-point arithmetic field for this value.
  164. */
  165. format;
  166. #format;
  167. // The actual value (accounting for decimals)
  168. #val;
  169. // A base-10 value to multiple values by to maintain the magnitude
  170. #tens;
  171. /**
  172. * This is a property so console.log shows a human-meaningful value.
  173. *
  174. * @private
  175. */
  176. _value;
  177. // Use this when changing this file to get some typing info,
  178. // but then switch to any to mask the internal type
  179. //constructor(guard: any, value: bigint, format: _FixedFormat) {
  180. /**
  181. * @private
  182. */
  183. constructor(guard, value, format) {
  184. assertPrivate(guard, _guard, "FixedNumber");
  185. this.#val = value;
  186. this.#format = format;
  187. const _value = toString(value, format.decimals);
  188. defineProperties(this, { format: format.name, _value });
  189. this.#tens = getTens(format.decimals);
  190. }
  191. /**
  192. * If true, negative values are permitted, otherwise only
  193. * positive values and zero are allowed.
  194. */
  195. get signed() { return this.#format.signed; }
  196. /**
  197. * The number of bits available to store the value.
  198. */
  199. get width() { return this.#format.width; }
  200. /**
  201. * The number of decimal places in the fixed-point arithment field.
  202. */
  203. get decimals() { return this.#format.decimals; }
  204. /**
  205. * The value as an integer, based on the smallest unit the
  206. * [[decimals]] allow.
  207. */
  208. get value() { return this.#val; }
  209. #checkFormat(other) {
  210. assertArgument(this.format === other.format, "incompatible format; use fixedNumber.toFormat", "other", other);
  211. }
  212. #checkValue(val, safeOp) {
  213. /*
  214. const width = BigInt(this.width);
  215. if (this.signed) {
  216. const limit = (BN_1 << (width - BN_1));
  217. assert(safeOp == null || (val >= -limit && val < limit), "overflow", "NUMERIC_FAULT", {
  218. operation: <string>safeOp, fault: "overflow", value: val
  219. });
  220. if (val > BN_0) {
  221. val = fromTwos(mask(val, width), width);
  222. } else {
  223. val = -fromTwos(mask(-val, width), width);
  224. }
  225. } else {
  226. const masked = mask(val, width);
  227. assert(safeOp == null || (val >= 0 && val === masked), "overflow", "NUMERIC_FAULT", {
  228. operation: <string>safeOp, fault: "overflow", value: val
  229. });
  230. val = masked;
  231. }
  232. */
  233. val = checkValue(val, this.#format, safeOp);
  234. return new FixedNumber(_guard, val, this.#format);
  235. }
  236. #add(o, safeOp) {
  237. this.#checkFormat(o);
  238. return this.#checkValue(this.#val + o.#val, safeOp);
  239. }
  240. /**
  241. * Returns a new [[FixedNumber]] with the result of %%this%% added
  242. * to %%other%%, ignoring overflow.
  243. */
  244. addUnsafe(other) { return this.#add(other); }
  245. /**
  246. * Returns a new [[FixedNumber]] with the result of %%this%% added
  247. * to %%other%%. A [[NumericFaultError]] is thrown if overflow
  248. * occurs.
  249. */
  250. add(other) { return this.#add(other, "add"); }
  251. #sub(o, safeOp) {
  252. this.#checkFormat(o);
  253. return this.#checkValue(this.#val - o.#val, safeOp);
  254. }
  255. /**
  256. * Returns a new [[FixedNumber]] with the result of %%other%% subtracted
  257. * from %%this%%, ignoring overflow.
  258. */
  259. subUnsafe(other) { return this.#sub(other); }
  260. /**
  261. * Returns a new [[FixedNumber]] with the result of %%other%% subtracted
  262. * from %%this%%. A [[NumericFaultError]] is thrown if overflow
  263. * occurs.
  264. */
  265. sub(other) { return this.#sub(other, "sub"); }
  266. #mul(o, safeOp) {
  267. this.#checkFormat(o);
  268. return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp);
  269. }
  270. /**
  271. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  272. * by %%other%%, ignoring overflow and underflow (precision loss).
  273. */
  274. mulUnsafe(other) { return this.#mul(other); }
  275. /**
  276. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  277. * by %%other%%. A [[NumericFaultError]] is thrown if overflow
  278. * occurs.
  279. */
  280. mul(other) { return this.#mul(other, "mul"); }
  281. /**
  282. * Returns a new [[FixedNumber]] with the result of %%this%% multiplied
  283. * by %%other%%. A [[NumericFaultError]] is thrown if overflow
  284. * occurs or if underflow (precision loss) occurs.
  285. */
  286. mulSignal(other) {
  287. this.#checkFormat(other);
  288. const value = this.#val * other.#val;
  289. assert((value % this.#tens) === BN_0, "precision lost during signalling mul", "NUMERIC_FAULT", {
  290. operation: "mulSignal", fault: "underflow", value: this
  291. });
  292. return this.#checkValue(value / this.#tens, "mulSignal");
  293. }
  294. #div(o, safeOp) {
  295. assert(o.#val !== BN_0, "division by zero", "NUMERIC_FAULT", {
  296. operation: "div", fault: "divide-by-zero", value: this
  297. });
  298. this.#checkFormat(o);
  299. return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp);
  300. }
  301. /**
  302. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  303. * by %%other%%, ignoring underflow (precision loss). A
  304. * [[NumericFaultError]] is thrown if overflow occurs.
  305. */
  306. divUnsafe(other) { return this.#div(other); }
  307. /**
  308. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  309. * by %%other%%, ignoring underflow (precision loss). A
  310. * [[NumericFaultError]] is thrown if overflow occurs.
  311. */
  312. div(other) { return this.#div(other, "div"); }
  313. /**
  314. * Returns a new [[FixedNumber]] with the result of %%this%% divided
  315. * by %%other%%. A [[NumericFaultError]] is thrown if underflow
  316. * (precision loss) occurs.
  317. */
  318. divSignal(other) {
  319. assert(other.#val !== BN_0, "division by zero", "NUMERIC_FAULT", {
  320. operation: "div", fault: "divide-by-zero", value: this
  321. });
  322. this.#checkFormat(other);
  323. const value = (this.#val * this.#tens);
  324. assert((value % other.#val) === BN_0, "precision lost during signalling div", "NUMERIC_FAULT", {
  325. operation: "divSignal", fault: "underflow", value: this
  326. });
  327. return this.#checkValue(value / other.#val, "divSignal");
  328. }
  329. /**
  330. * Returns a comparison result between %%this%% and %%other%%.
  331. *
  332. * This is suitable for use in sorting, where ``-1`` implies %%this%%
  333. * is smaller, ``1`` implies %%this%% is larger and ``0`` implies
  334. * both are equal.
  335. */
  336. cmp(other) {
  337. let a = this.value, b = other.value;
  338. // Coerce a and b to the same magnitude
  339. const delta = this.decimals - other.decimals;
  340. if (delta > 0) {
  341. b *= getTens(delta);
  342. }
  343. else if (delta < 0) {
  344. a *= getTens(-delta);
  345. }
  346. // Comnpare
  347. if (a < b) {
  348. return -1;
  349. }
  350. if (a > b) {
  351. return 1;
  352. }
  353. return 0;
  354. }
  355. /**
  356. * Returns true if %%other%% is equal to %%this%%.
  357. */
  358. eq(other) { return this.cmp(other) === 0; }
  359. /**
  360. * Returns true if %%other%% is less than to %%this%%.
  361. */
  362. lt(other) { return this.cmp(other) < 0; }
  363. /**
  364. * Returns true if %%other%% is less than or equal to %%this%%.
  365. */
  366. lte(other) { return this.cmp(other) <= 0; }
  367. /**
  368. * Returns true if %%other%% is greater than to %%this%%.
  369. */
  370. gt(other) { return this.cmp(other) > 0; }
  371. /**
  372. * Returns true if %%other%% is greater than or equal to %%this%%.
  373. */
  374. gte(other) { return this.cmp(other) >= 0; }
  375. /**
  376. * Returns a new [[FixedNumber]] which is the largest **integer**
  377. * that is less than or equal to %%this%%.
  378. *
  379. * The decimal component of the result will always be ``0``.
  380. */
  381. floor() {
  382. let val = this.#val;
  383. if (this.#val < BN_0) {
  384. val -= this.#tens - BN_1;
  385. }
  386. val = (this.#val / this.#tens) * this.#tens;
  387. return this.#checkValue(val, "floor");
  388. }
  389. /**
  390. * Returns a new [[FixedNumber]] which is the smallest **integer**
  391. * that is greater than or equal to %%this%%.
  392. *
  393. * The decimal component of the result will always be ``0``.
  394. */
  395. ceiling() {
  396. let val = this.#val;
  397. if (this.#val > BN_0) {
  398. val += this.#tens - BN_1;
  399. }
  400. val = (this.#val / this.#tens) * this.#tens;
  401. return this.#checkValue(val, "ceiling");
  402. }
  403. /**
  404. * Returns a new [[FixedNumber]] with the decimal component
  405. * rounded up on ties at %%decimals%% places.
  406. */
  407. round(decimals) {
  408. if (decimals == null) {
  409. decimals = 0;
  410. }
  411. // Not enough precision to not already be rounded
  412. if (decimals >= this.decimals) {
  413. return this;
  414. }
  415. const delta = this.decimals - decimals;
  416. const bump = BN_5 * getTens(delta - 1);
  417. let value = this.value + bump;
  418. const tens = getTens(delta);
  419. value = (value / tens) * tens;
  420. checkValue(value, this.#format, "round");
  421. return new FixedNumber(_guard, value, this.#format);
  422. }
  423. /**
  424. * Returns true if %%this%% is equal to ``0``.
  425. */
  426. isZero() { return (this.#val === BN_0); }
  427. /**
  428. * Returns true if %%this%% is less than ``0``.
  429. */
  430. isNegative() { return (this.#val < BN_0); }
  431. /**
  432. * Returns the string representation of %%this%%.
  433. */
  434. toString() { return this._value; }
  435. /**
  436. * Returns a float approximation.
  437. *
  438. * Due to IEEE 754 precission (or lack thereof), this function
  439. * can only return an approximation and most values will contain
  440. * rounding errors.
  441. */
  442. toUnsafeFloat() { return parseFloat(this.toString()); }
  443. /**
  444. * Return a new [[FixedNumber]] with the same value but has had
  445. * its field set to %%format%%.
  446. *
  447. * This will throw if the value cannot fit into %%format%%.
  448. */
  449. toFormat(format) {
  450. return FixedNumber.fromString(this.toString(), format);
  451. }
  452. /**
  453. * Creates a new [[FixedNumber]] for %%value%% divided by
  454. * %%decimal%% places with %%format%%.
  455. *
  456. * This will throw a [[NumericFaultError]] if %%value%% (once adjusted
  457. * for %%decimals%%) cannot fit in %%format%%, either due to overflow
  458. * or underflow (precision loss).
  459. */
  460. static fromValue(_value, _decimals, _format) {
  461. const decimals = (_decimals == null) ? 0 : getNumber(_decimals);
  462. const format = getFormat(_format);
  463. let value = getBigInt(_value, "value");
  464. const delta = decimals - format.decimals;
  465. if (delta > 0) {
  466. const tens = getTens(delta);
  467. assert((value % tens) === BN_0, "value loses precision for format", "NUMERIC_FAULT", {
  468. operation: "fromValue", fault: "underflow", value: _value
  469. });
  470. value /= tens;
  471. }
  472. else if (delta < 0) {
  473. value *= getTens(-delta);
  474. }
  475. checkValue(value, format, "fromValue");
  476. return new FixedNumber(_guard, value, format);
  477. }
  478. /**
  479. * Creates a new [[FixedNumber]] for %%value%% with %%format%%.
  480. *
  481. * This will throw a [[NumericFaultError]] if %%value%% cannot fit
  482. * in %%format%%, either due to overflow or underflow (precision loss).
  483. */
  484. static fromString(_value, _format) {
  485. const match = _value.match(/^(-?)([0-9]*)\.?([0-9]*)$/);
  486. assertArgument(match && (match[2].length + match[3].length) > 0, "invalid FixedNumber string value", "value", _value);
  487. const format = getFormat(_format);
  488. let whole = (match[2] || "0"), decimal = (match[3] || "");
  489. // Pad out the decimals
  490. while (decimal.length < format.decimals) {
  491. decimal += Zeros;
  492. }
  493. // Check precision is safe
  494. assert(decimal.substring(format.decimals).match(/^0*$/), "too many decimals for format", "NUMERIC_FAULT", {
  495. operation: "fromString", fault: "underflow", value: _value
  496. });
  497. // Remove extra padding
  498. decimal = decimal.substring(0, format.decimals);
  499. const value = BigInt(match[1] + whole + decimal);
  500. checkValue(value, format, "fromString");
  501. return new FixedNumber(_guard, value, format);
  502. }
  503. /**
  504. * Creates a new [[FixedNumber]] with the big-endian representation
  505. * %%value%% with %%format%%.
  506. *
  507. * This will throw a [[NumericFaultError]] if %%value%% cannot fit
  508. * in %%format%% due to overflow.
  509. */
  510. static fromBytes(_value, _format) {
  511. let value = toBigInt(getBytes(_value, "value"));
  512. const format = getFormat(_format);
  513. if (format.signed) {
  514. value = fromTwos(value, format.width);
  515. }
  516. checkValue(value, format, "fromBytes");
  517. return new FixedNumber(_guard, value, format);
  518. }
  519. }
  520. //const f1 = FixedNumber.fromString("12.56", "fixed16x2");
  521. //const f2 = FixedNumber.fromString("0.3", "fixed16x2");
  522. //console.log(f1.divSignal(f2));
  523. //const BUMP = FixedNumber.from("0.5");
  524. //# sourceMappingURL=fixednumber.js.map