Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 02-03-2013, 12:53 AM   PM User | #1
billboy
New Coder

 
Join Date: Feb 2013
Posts: 37
Thanks: 1
Thanked 0 Times in 0 Posts
billboy is an unknown quantity at this point
Implement JS NumberFormat Function

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
billboy is offline   Reply With Quote
Old 02-03-2013, 03:19 AM   PM User | #2
Airblader
Regular Coder

 
Join Date: Jan 2013
Location: Germany
Posts: 368
Thanks: 3
Thanked 44 Times in 44 Posts
Airblader can only hope to improve
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..
Airblader is offline   Reply With Quote
Old 02-03-2013, 04:47 AM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,998 Times in 3,967 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
This is crazy:
Code:
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..
Old Pedant is offline   Reply With Quote
Old 02-03-2013, 05:20 AM   PM User | #4
billboy
New Coder

 
Join Date: Feb 2013
Posts: 37
Thanks: 1
Thanked 0 Times in 0 Posts
billboy is an unknown quantity at this point
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'

Last edited by billboy; 02-03-2013 at 05:35 AM..
billboy is offline   Reply With Quote
Old 02-03-2013, 05:56 AM   PM User | #5
billboy
New Coder

 
Join Date: Feb 2013
Posts: 37
Thanks: 1
Thanked 0 Times in 0 Posts
billboy is an unknown quantity at this point
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;
  };
}
billboy is offline   Reply With Quote
Old 02-03-2013, 11:22 AM   PM User | #6
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,044
Thanks: 197
Thanked 2,412 Times in 2,390 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
See the answer you were given in the thread you have hijacked.

http://www.codingforums.com/showthread.php?t=286939
__________________

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.
Philip M is offline   Reply With Quote
Old 02-03-2013, 09:47 PM   PM User | #7
billboy
New Coder

 
Join Date: Feb 2013
Posts: 37
Thanks: 1
Thanked 0 Times in 0 Posts
billboy is an unknown quantity at this point
Quote:
Originally Posted by Philip M View Post
See the answer you were given in the thread you have hijacked.

http://www.codingforums.com/showthread.php?t=286939
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"
billboy is offline   Reply With Quote
Old 02-04-2013, 08:11 AM   PM User | #8
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,044
Thanks: 197
Thanked 2,412 Times in 2,390 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
Quote:
Originally Posted by billboy View Post
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.
Philip M is offline   Reply With Quote
Old 02-04-2013, 08:31 PM   PM User | #9
billboy
New Coder

 
Join Date: Feb 2013
Posts: 37
Thanks: 1
Thanked 0 Times in 0 Posts
billboy is an unknown quantity at this point
Quote:
Originally Posted by Philip M View Post
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

Thanks
billboy is offline   Reply With Quote
Old 02-04-2013, 09:14 PM   PM User | #10
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,465
Thanks: 0
Thanked 499 Times in 491 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by billboy View Post
Yes but the OP was on implementing js from external file?
That's how ALL JavaScript should be implemented.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 07:13 AM.


Advertisement
Log in to turn off these ads.