javascript乘以小数点

时间:2017-07-30 10:34:38

标签: javascript validation

我的 MultiplyChk验证效果很好,但是当我使用小数点它停止工作时。 第一个示例的验证有效,但第二个示例没有。 两个检查都是乘法验证。有人可以帮帮我吗?

function formValidator() {
    var Two = document.getElementById('Two'); //Category
    var Total = document.getElementById('Total'); //Category
    var ExVAT = document.getElementById('ExVAT'); //exVAT
    var AmtPaid = document.getElementById('AmtPaid'); //AmtPaid

    if (MultiplyChk(Two, Total, "Total Amt must be double the first amount",
            "The first calculation is correct, click OK for 2nd calculation")) {
        if (isVAT(ExVAT, AmtPaid, "incorrect or validation not working correctly", "YES! Correct!")) {
            return true;
        }
    }
    return false;
}

function MultiplyChk(elem, elem2, helperMsg, correctMsg) {
    if ((elem2.value) == (elem.value * 2)) {
        alert(correctMsg);
        return true;
    } else {
        alert(helperMsg);
        elem.focus();
        return false;
    }
}

function isVAT(elem, elem2, helperMsg, correctMsg) {
    if ((elem2.value) == (elem.value * 1.14)) {
        alert(correctMsg);
        return true;

    } else {
        alert(helperMsg);
        elem.focus();
        return false;
    }
}

<form  action="alert('Correct!');"  onsubmit="return formValidator()" >
    This one works:<br>
    <input type="text" id="Two" name="Two" value="2"> *  2 =
    <input type="text" id="Total" name="Total" value="4">
    <br><br>
 
    but this validation does not work:<br><br>
    eg. R100 ex VAT = R114incl VAT<br>
    Ex VAT: <input type="text" id="ExVAT" size = 7 name="ExVAT" value="10">        <br>
    *1.14 = <br>
    AmtPaid: <input type="text" id="AmtPaid" name="AmtPaid" value="11.4">
    <br>
    <br>
    <input type="submit" value="Submit/Save"  onsubmit='return formValidator()'  style="width:300px;height:30px" />
</form>

1 个答案:

答案 0 :(得分:1)

这是浮点数的工作原理。他们不准确。所以你需要一个小的容差,例如:

if(Math.abs(elem2.value-elem.value*2)<Number.EPSILON){

about EPSILON

或使用直接容差量:

 if(Math.abs(elem2.value-elem.value*2)<0.0001){

In action