views:

172

answers:

2

Hello!

I found i little snipet on internet, about PMT calculate.

function PMT(i, n, p) {
 return i * p * Math.pow((1 + i), n) / (1 - Math.pow((1 + i), n));
}
function CalculatePMTFromForm(idLoanAmount, idAnnualInterestRate, idMonths, idResult) {
 var i = jQuery('#' + idAnnualInterestRate).val() / 1200;
 var n = jQuery('#' + idMonths).val();
 var p = jQuery('#' + idLoanAmount).val();
 var pmt = PMT(i, n, -p);
jQuery('#' + idResult).val(pmt.toFixed(2));
}
function performCalc() {
 CalculatePMTFromForm('LoanAmount', 'InterestRate', 'Months', 'Payment');
}
jQuery(document).ready(function() { performCalc(); jQuery('.calc').keyup(performCalc); });

When the page is load, in the result input box I see "NaN" , and when i tpye some irrelevant number then "-Infinity" msg appear. I search to "NaN" in files and i found in jquery.js, but after I modify, nothing change. And I can't find Infinity

How can I change this messages?

Edit

Calling code:-

function performCalc() {
  CalculatePMTFromForm('LoanAmount', 'InterestRate', 'Months', 'Payment');
}

jQuery(document).ready(function() {
  performCalc(); jQuery('.calc').keyup(performCalc);
});

This is worked for me:

if(pmt>0 && pmt<Number.MAX_VALUE) {jQuery('#' + idResult).val(pmt.toFixed(2));}
A: 

NaN means "Not A Number".

Make sure you check for each input value whether it is numeric. Throw an error message if one is not, or set it to 0, depending on whether it's essential to your calculation or not.

A good collection of the best ways to check a value for whether it's numeric is this SO question: Validate numbers in JavaScript - IsNumeric()

Pekka
i dont really understand. Even if i check the input fields validity, the user can write wrong format, just get a msg to type "number or smtng"...But till the user can tpye wrong character then get a message in result input field NaN. I will check the input field, but i need to turn of somehow the NoN and Infinity message.
Holian
A: 

Try it like this:-

function CalculatePMTFromForm(idLoanAmount, idAnnualInterestRate, idMonths, idResult) {
 var i = parseFloat($('#' + idAnnualInterestRate).val()) / 1200;
 var n = parseFloat($('#' + idMonths).val());
 var p = parseFloat($('#' + idLoanAmount).val());
 var pmt = PMT(i, n, -p);
 $('#' + idResult).val(pmt.toFixed(2));
}

The .val() is likely returning a string type not a number type.

AnthonyWJones
i tried but nothing changed.
Holian