简体   繁体   English

小于条件不适用于浮点数

[英]less than conditional not working for floats

heres my jquery/javascript code:这是我的 jquery/javascript 代码:

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:假设 html 如下:

<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.无论出于何种原因,即使 p_cash 范围内的内容大于 p_sale 范围内的内容,我仍然会收到警报。

i don't get it.我不明白。

toFixed converts the number to a fixed string. toFixed将数字转换为固定字符串。 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 .通常,这仍然适用于10.0020.00之类的值 - 但绝对不适用于128.503.14

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM