Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  • The precise option is added to the pjs.define() configuration. This makes it so that num1, num2, and num3, refer to decimal.js values instead of native JS numbers.

  • The number literals are specified as strings instead of numbers, to avoid precision loss. Precise decimal values can also accept numbers, but you should strings for values with more than 15 digits.

  • The arithmetic coding is done with num1.plus(num2) instead of num1 + num2.

    • Precise decimal values are coerced to JavaScript strings, so in this case coding num1 + num2 would result in a string 222222222222222.3333444444444444444.2222


Using pjs.math to Evaluation Math Expressions

Another option for precise decimal arithmetic is to use pjs.math to evaluate a template literal string as a math expression. Precise decimal and other numeric values can be inserted into the template literal as place holders. For example:

Code Block
  pjs.define("num1", { type: "packed", length: 22, decimals: 2, precise: true, initValue: "10000000000000000000.75" });
  pjs.define("num2", { type: "packed", length: 22, decimals: 2, precise: true, initValue: "20000000000000000000.25" });
  pjs.define("result", { type: "packed", length: 22, decimals: 2, precise: true });

  result = pjs.math`(${num1} + ${num2}) / 4`;
  console.log(String(result)); // Output: 7500000000000000000.25

Using Precise Decimal Without Strongly Typed Fields

...