Showing posts with label How to calculate EMI using JQuery. Show all posts
Showing posts with label How to calculate EMI using JQuery. Show all posts

Sunday, 10 November 2013

How to calculate EMI using JQuery

Formula: EMI = (P * r/12) * [ (1+r/12)^n] / [ (1+r/12)^n-1]

Where,
P = Outstanding Principle
r = Interest Rate
n = Tenure (in months)


Following is the JS Code to calculate EMI

<script type="text/javascript">
function calculateEMI(obj) {                                               
 // Formula: 
 // EMI = (P * R/12) * [ (1+R/12)^N] / [ (1+R/12)^N-1]                               
                
 // isNaN(isNotaNumber): Check whether the value is Number or Not                
    if (!isNaN(obj.value) && obj.value.length !== 0) {
                    
    var emi = 0;
    var P = 0;
    var n = 1;
    var r = 0;                                       
                    
   // parseFloat: This function parses a string 
  // and returns a floating point number
    if($("#outstanding_principle").val() !== "")
       P = parseFloat($("#outstanding_principle").val());
                   
                        
    if ($("#interest_rate").val() !== "") 
      r = parseFloat(parseFloat($("#interest_rate").val()) / 100);

    if ($("#tenure").val() !== "")
        n = parseFloat($("#tenure").val());
                    
    // Math.pow(): This function returns the value of x to power of y 
    // Example: (5^2)
                    
    // toFixed: Convert a number into string by keeping desired decimals                   
                    
    if (P !== 0 && n !== 0 && r !== 0)
    emi = parseFloat((P * r / 12) * [Math.pow((1 + r / 12), n)] / [Math.pow((1 + r / 12), n) - 1]);
              
    $("#emi").val(emi.toFixed(2));
                
  }
}
</script>

And Following is the HTML code
<table>
   <tr>
     <th>Outstanding Principle</th>
     <th>Interest Rate (%)</th>
     <th>Tenure (in Months)</th>
     <th>EMI</th>
   </tr>
   <tr>
     <td>
       <input type="text" id="outstanding_principle" onchange="calculateEMI(this);">
     </td>
     <td>
       <input type="text" id="interest_rate" onchange="calculateEMI(this);">
     </td>
     <td>
       <input type="text" id="tenure" onchange="calculateEMI(this);">
     </td>
     <td>
       <input type="text" readonly="true" id="emi">
     </td>
 </tr>                
</table>

Demo