Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    New Coder
    Join Date
    Feb 2013
    Posts
    44
    Thanks
    2
    Thanked 0 Times in 0 Posts

    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

  • #2
    Regular Coder
    Join Date
    Jan 2013
    Location
    Germany
    Posts
    578
    Thanks
    4
    Thanked 77 Times in 77 Posts
    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.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    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 ... }
    Last edited by Old Pedant; 02-03-2013 at 04:50 AM.
    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.

  • #4
    New Coder
    Join Date
    Feb 2013
    Posts
    44
    Thanks
    2
    Thanked 0 Times in 0 Posts
    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.

  • #5
    New Coder
    Join Date
    Feb 2013
    Posts
    44
    Thanks
    2
    Thanked 0 Times in 0 Posts
    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;
      };
    }

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,909
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    See the answer you were given in the thread you have hijacked.

    JavaScript Functions in separate .js files not working properly

    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.

  • #7
    New Coder
    Join Date
    Feb 2013
    Posts
    44
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Philip M View Post
    See the answer you were given in the thread you have hijacked.

    JavaScript Functions in separate .js files not working properly
    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"

  • #8
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,909
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    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.

  • #9
    New Coder
    Join Date
    Feb 2013
    Posts
    44
    Thanks
    2
    Thanked 0 Times in 0 Posts
    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

  • #10
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,609
    Thanks
    0
    Thanked 645 Times in 635 Posts
    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/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •