0

For data below when I try to add prebalance, amount to match with balance, why I am getting wrong sum value. How can I get the correct values.

{
    "prebalance": -2865.59,
    "amount": 3000.00,
    "balance": 134.41
},
{
    "prebalance": -1865.59,
    "amount": 2000.00,
    "balance": 134.41
}
]

JQ Play link for sample data.

https://jqplay.org/s/T4gL4kOkj7X

peak
  • 105,803
  • 17
  • 152
  • 177
Madhuprathap
  • 209
  • 1
  • 3
  • 15
  • Does this answer your question? [How I can round digit on the last column to 2 decimal after a dot using JQ?](https://stackoverflow.com/questions/46117049/how-i-can-round-digit-on-the-last-column-to-2-decimal-after-a-dot-using-jq) – jthulhu Aug 23 '22 at 15:45
  • 1
    The sum is correct, just not precise, a (general) limitation of floating-point arithmetics. You should always consider rounding, when dealing with (especially comparing to) floating-point numbers (or operations potentially producing them). – pmf Aug 23 '22 at 16:09
  • Can you help me to round it off two decimal places? i.e. 134.40999999999985 to 134.41 My number can be of any length not just 3 digits. I have tried multiple Math options. – Madhuprathap Aug 23 '22 at 16:31

1 Answers1

1

The sum is correct, just not precise, a (general) limitation of floating-point arithmetics. You should always consider rounding, when dealing with (especially comparing to) floating-point numbers (or operations potentially producing them).

Can you help me to round it off two decimal places? i.e. 134.40999999999985 to 134.41 My number can be of any length not just 3 digits.

Round the numbers for display:
map(
  .sum = .prebalance + .amount
  | .sum |= (. * 100 | round / 100)
)
[
  {
    "prebalance": -2865.59,
    "amount": 3000,
    "balance": 134.41,
    "sum": 134.41
  },
  {
    "prebalance": -1865.59,
    "amount": 2000,
    "balance": 134.41,
    "sum": 134.41
  }
]

Demo

Compare the absolute difference to a given epsilon for equality tests:
1e-9 as $epsilon | map(
  .sum = .prebalance + .amount
  | .equal = (.sum - .balance | fabs < $epsilon)
)
[
  {
    "prebalance": -2865.59,
    "amount": 3000,
    "balance": 134.41,
    "sum": 134.40999999999985,
    "equal": true
  },
  {
    "prebalance": -1865.59,
    "amount": 2000,
    "balance": 134.41,
    "sum": 134.41000000000008,
    "equal": true
  }
]

Demo

pmf
  • 24,478
  • 2
  • 22
  • 31