...
To help with JavaScript decimal arithmetic issues discussed here, Profound.js provides a few solutions:
...
The
precise
option is added to thepjs.define()
configuration. This makes it so thatnum1
,num2
, andnum3
, refer todecimal.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 ofnum1 + num2
.Precise decimal values are coerced to JavaScript strings, so in this case coding
num1 + num2
would result in a string222222222222222.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
Precise decimal values can be used without strongly typed fields by importing the decimal.js library and using like this:
Code Block |
---|
const Decimal = require("decimal.js");
let num1 = new Decimal("0.1");
let num2 = new Decimal("0.2");
let result = num1.plus(num2); |
See the decimal.js documentation for more details.