jwadhams / json-logic-js

Build complex rules, serialize them as JSON, and execute them in JavaScript
MIT License
1.27k stars 139 forks source link

Problem with sum number #65

Closed bigjorjao closed 5 years ago

bigjorjao commented 5 years ago

I have this rule {"reduce":[ {"var":"myArray"}, {"+":[{"+" : {"var":"current"}}, {"var":"accumulator"}]}, 0 ]} Values: {"myArray":[0.1,0.7]} But Output: 0.7999999999999999 why? should not give 0.8? Is there any expression to round up?

if i have {"myArray":[0.1,0.3]} --> output: 0.4 OK but if {"myArray":[11.11,22.63]} --> output: 33.739999999999995 ??

jwadhams commented 5 years ago

That's not a JsonLogic problem, it's a floating point problem. Try it out directly in Node or your browser's console, I think you'll be unpleasantly surprised:

$ node
> 0.1 + 0.7
0.7999999999999999

Check out this handy explainer: https://0.30000000000000004.com/

jwadhams commented 5 years ago

Oh, sorry to answer your second question, no JsonLogic doesn't ship with a rounder, but you could import the JavaScript math library like:

jsonLogic.add_operation('Math', Math);

and then tweak your rule to use round or ceil or floor as you wish:

{"Math.floor":[
  {"reduce":[
    {"var":"myArray"},
    {"+":[{"+" : {"var":"current"}}, {"var":"accumulator"}]},
    0
  ]}
]}