Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do older versions of javascript evaluate ("-1" < 0) as false?

Tags:

javascript

A bit of js on my brother's eCommerce site computes and stores transaction totals every time someone checks out. Periodically, a negative value is stored for tracker_total_amount. While he tries to work out why, he's decided to hard code an override which should address the ~0.1% of transactions with nonsensical values. It looks like this:

var tracker_total_amount = parseFloat(tracker.total_amount).toFixed(2);
    if(tracker_total_amount < 0){
        tracker_total_amount = 0;
    }

Negative values have continued to show up in the system.

Original theory:

I don't think he should be using .toFixed, because that's going to cast tracker_total_amount as a string - which, in my mind, would have stopped the if < 0 condition working as expected. I was quite happy with this explanation until I tested it and the override worked. See here: http://jsfiddle.net/yXTrz/

New theory:

Different users are running different versions of javascript. Some very small subset use an ancient version of javascript which (instead of helpfully converting the string to a float like mine is doing) continue to treat it as a string and always evaluate tracker_total_amount as being > 0, preventing the override from firing.

Question:

Did older version of javascript behave in this way? Could some users still be running those old versions? Best of all - is there a way I can simulate legacy versions of javascript to prove my theory?

Edit: I should point out all the important stuff (payment etc) relies on a server side calculated value. The numbers here are just what's stored in Google Analytics afterwards, so - while it's possible to manipulate - the results wouldn't be too atrocious.

like image 710
mcl Avatar asked Sep 09 '13 07:09

mcl


1 Answers

You can get very small negative values to pass through, ie -0.001 because the value is being set to fixed. Not sure what kind of negatives you are seeing, but anything that goes outside of the fixed value as a negative will allow the negative through. Sorry, should be more clear, if there are further calculations that do not use the returned value and not the original value... The returned value would be -0.00... So if this is just being used as a test...

like image 103
Kevin Avatar answered Oct 16 '22 19:10

Kevin