scarhand
scarhand

Reputation: 4337

less than conditional not working for floats

heres my jquery/javascript code:

amount_sale = parseFloat($('#p_sale span').html()).toFixed(2);
amount_cash = parseFloat($('#p_cash span').html()).toFixed(2);

if (amount_cash < amount_sale)
{
    alert('Cash amount must be greater than or equal to sale amount');
    return;
}

lets say that the html is as follows:

<p id="p_sale">Sale: <span>10.00</span></p>
<p id="p_cash">Cash: <span>20.00</span></p>

for whatever reason, even if the contents within the p_cash span is greater than the contents within the p_sale span, i still get the alert.

i don't get it.

Upvotes: 0

Views: 2717

Answers (1)

Ry-
Ry-

Reputation: 225074

toFixed converts the number to a fixed string. Before it, you just have a number, without precision. I'm sure you want:

amount_sale = parseFloat($('#p_sale span').html()).toFixed(2);
amount_cash = parseFloat($('#p_cash span').html()).toFixed(2);

if (amount_cash < amount_sale)
{
    alert('Cash amount must be greater than or equal to sale amount');
    return;
}

Normally, that would still work with values like 10.00 and 20.00 - but definitely not with 128.50 and 3.14.

Upvotes: 5

Related Questions