boolean logic - Odd JavaScript Behavior When Comparing Numbers Larger than 1000 -
i wrote javascript function supposed check if amount greater 0 , less amount. example, if total amount due $800.00, , user tries pay $1100, want function first check amount being paid ($1100) greater 0 (true) , amount being paid less total amount due (false). pretty sure logic fine, function hasn't been working correctly:
function validate_payment_amount() { var payment_amt = get_amount_paying(); // 1100.00 var amt_due = get_amount_due(); // 800.00 console.log('is ' + payment_amt + ' greater 0?: ' + (payment_amt > 0)); console.log('&&'); console.log('is ' + payment_amt + ' less or equal ' + amt_due + '?: ' + (payment_amt <= amt_due)); return payment_amt > 0 && payment_amt <= amt_due; }
the function evaluates correctly if payment_amount
less 1000, here console output:
is 999.00 greater 0?: true && 999.00 less or equal 892.50?: false
so above works fine. however, when give number greater 1000, console displays:
is 1001.00 greater 0?: true && 1001.00 less or equal 892.50?: true
can please shed light on this?
edit: get_amount_paying()
, get_amount_due()
:
function get_amount_due() { return parsefloat($("#still_due").data('amount')).tofixed(2); } function get_amount_paying() { return parsefloat($("#make_payment").val()).tofixed(2); }
your output gives away fact strings - printing actual number type never have extraneous 0s. seeing 892.50
when printing number impossible.
.tofixed()
returns string, not number btw.
it works > 0
, because when comparing string > number
, string automatically parsed number before comparison.
it doesn't work payment_amt <= amt_due
because both strings, string comparison done , nothing parsed numeric value.
try
function get_amount_due() { return parsefloat($("#still_due").data('amount')) } function get_amount_paying() { return parsefloat($("#make_payment").val()) }
the difference removal of tofixed
, useless here.
Comments
Post a Comment