我正在处理系统的计费部分,我使用 JavaScript 将一个事件放入我的 TextBox
中,并且我有两个文本框。首先是 cashonhand
和 change
文本框。但我想知道为什么两个文本框之间的比较没有给我正确的答案。这是我的代码:
$(document).ready(function () {
$(document).on('click', '.btn-pay-bill', function () {
var cash = parseFloat(Number($('.cashonhand').val())).toFixed(2);
var amtdue = parseFloat(Number($('.amtdue').text())).toFixed(2);
if (cash <= amtdue) {
alert(cash + ' ' + amtdue + ' ' +"Insufficient Cash!!!");
return false;
}
if (cash >= amtdue) {
return true;
}
return false;
});
那么我在这里错过了什么?以下是我将 100,000
与 78,200.00
进行比较时的输出:
最佳答案
您正在按字母顺序而不是数字进行比较。
请注意.toFixed()
returns a string :
block 引用>Returns
A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place.
您需要在调用
.toFixed()
之前进行此比较var cash = parseFloat(Number($('.cashonhand').val())); var amtdue = parseFloat(Number($('.amtdue').text())); if (cash <= amtdue) { alert(cash.toFixed(2) + ' ' + amtdue.toFixed(2) + ' ' +"Insufficient Cash!!!"); return false; }
您只需调用
.toFixed()
即可无论您在 UI 中显示数字,还是创建该值的单独字符串版本,例如sCash
和sAmtDue
或其他什么。
关于Javascript 比较无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22415849/