2

my MultiplyChk validation works nicely but the moment I use a decimal point it stops working. Validation on 1st example works but not on the 2nd example. both checks are multiplication validations. Can somebody help me please?

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 Answer 1

1

Thats how floating point numbers work. Theyre not exact. So you need to have a small tolerance e.g.:

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

about EPSILON

or using a direct tolerance amount:

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

In action

Sign up to request clarification or add additional context in comments.

3 Comments

Hmm. Looks complicated. Sieht kompliziert aus. Is there a solution - maybe using rounding? Answers dont need to be perfect.
@clark superman naja, so kompliziert ist das doch gar nicht ... ;) , runden wäre zu ungenau z.B: (0.3-0.2) wäre gerundet auch 0 ...
Must I now integrate the EPSILON number into the formula so that it works?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.