Clark Superman
Clark Superman

Reputation: 373

javascript multiplying with decimal points

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>

Upvotes: 2

Views: 51

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138367

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

Upvotes: 1

Related Questions