Hi guys I am brand new to JS and building a small calculator project just to learn:
Calculator is working and I a now trying to implement a Format function I got by googling. I am obviously doing something wrong because all my attempts fail and in fact stop the rest of my JS from running
Here is what I have:
The line in red is my attempt at implementing the formatDollar( ) function
Can someone show me where I am going wrong
Thanks
Code:
<script type="text/javascript">
<!--
function formatDollar(value) {
var p = num.toFixed(2).split(".");
return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
return num + (i && !(i % 3) ? "," : "") + acc;
}, "") + "." + p[1];
}
function centNotation(value)
{
dollars = Math.floor(value); // chop floating point portion
cents = Math.floor((value % 1) * 100); // and chop everything else
if (cents < 10) cents = "" + cents + "0";
return(dollars + "." + cents);
}
function validInt(value)
{
for (var i=0; i < value.length; i++) {
var c = value.charAt(i);
if ((c < '0' || c > '9') && c != '.') {
alert("There's a problem: all values herein must " +
"be numbers only, and " + value + " has an unacceptable character " +
"'" + c + "'");
return(false);
}
}
return(true);
}
function myPaymentCalc()
{
var interestRate = document.debtcalc.interest.value,
monthlyPayment = document.debtcalc.monthlypayment.value,
principal = document.debtcalc.principal.value,
accumulatingInterest = 1;
if (! validInt(interestRate) || ! validInt(monthlyPayment) ||
! validInt(principal))
return(false);
if (interestRate == 0 || monthlyPayment == 0 || principal == 0) {
alert("You need to specify your monthly payment, credit card " +
"interest rate and current debt amount before I can calculate " +
"how long it'll take for you to pay off your debt.");
return(false);
}
interestRate = (interestRate > 1)? interestRate / 100.0 : interestRate;
monthlyInterestRate = interestRate / 12;
if (principal * monthlyInterestRate > monthlyPayment) {
monthlyrate = "$" + centNotation(principal * monthlyInterestRate);
permonthPayment = "$" + centNotation(monthlyPayment);
alert("You've got a fundamental problem: your monthly payment of " +
permonthPayment + " is less than the interest added each month " +
"(which is " + monthlyrate + ") and you will never " +
"pay off this debt. It might be a good time to call your creditors.");
return(false);
}
interimVal1 = monthlyPayment - (monthlyInterestRate * principal)
numberOfPayments = (Math.log(monthlyPayment) - Math.log(interimVal1)) /
Math.log(1+monthlyInterestRate);
numberOfPayments = Math.ceil(numberOfPayments);
interimVal2 = Math.pow((monthlyInterestRate+1), (numberOfPayments-1));
remaining = (principal * interimVal2) -
(monthlyPayment/monthlyInterestRate) * (interimVal2 - 1);
totalPayment = monthlyPayment *(numberOfPayments-1) + remaining;
payments = numberOfPayments;
totalpayment = "$" + centNotation(totalPayment);
totalpaymentamt= formatDollar(totalpayment);
interestPaid = "$" + centNotation(totalPayment-principal);
alert("Given these figures, you'll end up having " + payments +
" payments and pay a total of " + totalpayment + ", of which " +
interestPaid + " is interest.");
document.debtcalc.numberofpayments.value = payments;
document.debtcalc.totalpayments.value = totalpayment;
document.debtcalc.intpmt.value = interestPaid;
}
// -->
</script>
Last edited by VIPStephan; 02-03-2013 at 09:50 PM..
Reason: added code BB tags
Did you take a look at the formatDollar function? It's pretty obvious that it cannot work if you name the parameter "value" in the head, but the function tries to work on a variable named "num". It just doesn't fit. There might be more wrong, but I didn't look further into it as this is the first mistake. Once you fixed this, please use the console to check what error you are getting – maybe you can fix it yourself.
Also, when you post source code, please use the [ code ] tags to that it looks better and is readable.
Last edited by Airblader; 02-03-2013 at 03:21 AM..
function validInt(value)
{
for (var i=0; i < value.length; i++) {
var c = value.charAt(i);
if ((c < '0' || c > '9') && c != '.') {
alert("There's a problem: all values herein must " +
"be numbers only, and " + value +
" has an unacceptable character " + "'" + c + "'");
return(false);
}
}
return(true);
}
validInt??? Integers do *NOT* have decimal points, so what in the world is the test for period doing in there?
On top of that, as written that code would *ALLOW* input such as ".........." or "3........9" or "3.999999999999", none of which make a lot of sense.
If you want to check for a valid number--and here I will assume it is to be no more than 2 digits after the decimal point (i.e., dollars and cents) then:
Code:
function validNum( value )
{
if ( ( /^\-?(\.\d\d?|\d+(\.\d?\d?)?)$/ ).test( value ) { return true; }
document.getElementById("errorMessage") =
"That is not a valid dollars and cents value";
return false;
}
The \-? in red is optional, if you want to allow negative numbers.
Notice that this also avoids the use of alert( ), which is obsolete.
But if you aren't so fussy--if you *WILL* allow numbers such as 3.9999999 or 13E2--then let JS test for you:
Code:
if ( isNaN( value ) ) { ... not a valid number ... } else { ... valid ... }
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Last edited by Old Pedant; 02-03-2013 at 04:50 AM..
Thanks Airblader I changed the parameter to num still not working and i have know Idea how to use "console" but will google and look into that
Thanks Old Pedant , that was also a piece of code I found googling, I actually do want to allow for decimals even though the function says "validInt" but thanks for explaing the other problems, once i figure out the problem with the question in my original post I will move onto that
Figured out how to get debugger in IE and there is an error
SCRIPT438: Object doesn't support property or method 'reduce'
Found a work around to the error message with this piece of code:
Code:
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(accumulator){
if (this===null || this===undefined) throw new TypeError("Object is null or undefined");
var i = 0, l = this.length >> 0, curr;
if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."
throw new TypeError("First argument is not callable");
if(arguments.length < 2) {
if (l === 0) throw new TypeError("Array length is 0 and no second argument");
curr = this[0];
i = 1; // start accumulating at the second element
}
else
curr = arguments[1];
while (i < l) {
if(i in this) curr = accumulator.call(undefined, curr, this[i], i, this);
++i;
}
return curr;
};
}
I didnt ask another question, I posted what appeared to be a soluton for others to see.
Wasn't aware I hijacked a thread, I asked a question that was relevant to the OP question in that thread. My apologies if that was not appropriate
"Supreme Master Coder"
I didnt ask another question, I posted what appeared to be a soluton for others to see.
Wasn't aware I hijacked a thread, I asked a question that was relevant to the OP question in that thread. My apologies if that was not appropriate
"Supreme Master Coder"
You asked "How can you get the value from a JS function that is in a seperate file to an inputbox on another page?". That is termed hijacking. Prefer to start your own thread if you want to raise a new issue.
__________________
All the code given in this post has been tested and is intended to address the question asked.
Unless stated otherwise it is not just a demonstration.
You asked "How can you get the value from a JS function that is in a seperate file to an inputbox on another page?". That is termed hijacking. Prefer to start your own thread if you want to raise a new issue.
Yes but the OP was on implementing js from external file?
Anyway, again my apologies, I certainly didnt intend to "hijack" anyones post, in the future I will start a new post