Why is rfd_total > max_rfd true? I don't understand how rfd_total can be greater than max_rfd in the following code:
max_rfd = parseFloat(jQuery('#mx-rfd_'+order_id).val()).toFixed(2);
rfd_total = parseFloat(items_total+tax_total+shipping+allowances*1).toFixed(2);
if( rfd_total > max_rfd)
{ if(isNaN(rfd_total)) alert('rfd_total isNaN'); // not triggered
if(isNaN(max_rfd)) alert('max_rfd isNaN'); // not triggered
alert(rfd_total); // alerts 51.16
alert(max_rfd); // alerts 102.32
return false;
}
It's because rfd_total an max_rfd are Strings.
You will notice that "51.16" > "102.32" returns true.
toFixed() returns a string.
You will need to coerce your variables to numbers, which you can find out how to do with a quick search.
Or you can keep your code clean and do it properly using a function such as this one
function decimalRoundTo(n, decimalPlaces) {
var d = Math.pow(10, decimalPlaces);
return Math.round(n*d)/d;
}
isNaN returns false. That is why your alerts aren't triggered. I've added a bit more to my answer btw - Griffin 2012-04-05 00:54
isNaN attempts to coerce the input parameter to a number. isNaN("12.13") returns false, but isNaN("hello") returns true - Griffin 2012-04-05 01:00
string * number in your code. Glad I could help - Griffin 2012-04-05 01:07
+rfd_total > +max_rfd is sufficient, or if a more explicit converion is required, then something like: Number(rfd_total) > Number(max_rfd) will do - RobG 2012-04-05 02:06
function decimalRoundTo(n, places) {return Number(n.toFixed(places));}. But I don't think that's required since the code itself is no longer than the call and for accuracy's sake, numbers should only be rounded for presentation. So what's the point - RobG 2012-04-05 14:32