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