Solved

I get NAN not a number when I enter 0 zero in the money field

Posted on 2007-12-04
5
357 Views
Last Modified: 2010-04-21
Hello Everyone, this function computes my percentages, but if I enter 0 (zero)  in the money field I get NAN in the percentage field, now I knwo the total percentage needs to be 100% at all times but NAN is not good, can the field remain blank ?

Or is there another way to fix this problem?

<script>

   //------------------------------------------------------------------

  // Name: CurToNum()

  // Role: Convert specified currency value to the equivalent numeric

  //       value.

  //------------------------------------------------------------------
 

  function CurToNum( val ) {

    val = val.replace(/\$|\,/g,'');

    return parseFloat( val );

  }
 

    //------------------------------------------------------------------

  // Name: formatCurrency()

  // Role: Convert specified numeric value to the equivalent currency

  //       value.

  //------------------------------------------------------------------

  function formatCurrency( num ) {

    num = num.toString().replace(/\$|\,/g,'');

    if( isNaN( num ) )

      num = "0";

    sign = ( num == ( num = Math.abs( num ) ) );

    num = Math.floor( num * 100 + 0.50000000001 );

    cents = num % 100;

    num = Math.floor( num / 100 ).toString();

    if ( cents < 10 )

      cents = "0" + cents;

    for ( var i = 0; i < Math.floor( ( num.length - ( 1 + i ) ) / 3 ); i++ )

      num = num.substring( 0, num.length -( 4 * i + 3 ) ) + ',' +

        num.substring( num.length - ( 4 * i + 3 ) );

    return ( ( ( sign ) ? '' : '-' ) + num  );

  }

 

  //------------------------------------------------------------------

  // Name: field()

  // Role: Locate the DOM element having the specified id attribute.

  //------------------------------------------------------------------

  function field( id ) {

    var obj = document.getElementById( id );

 

    if ( obj == null ) {

      alert( 'Specified field with id "' + id + '" not found.' );

    }

    return obj;

  }

 

  //------------------------------------------------------------------

  // Global arrays of ids of the data, and associated percentage

  // fields, and the ids of the overall total output field, as well as

  // the totalPercentage output field.

  //------------------------------------------------------------------

  var dataIds = 'POEMoney,LandMoney'.split( ',' );

  var perIds  = 'POEPercentage,LandPercentage'.split( ',' );

  var totalId = 'TotalMoney';

  var totalPercentId = 'TotalPercentage';

  

  //------------------------------------------------------------------

  // Name: Compute()

  // Role: Calcuate the total of the currency fields, then display the

  //       associated percentage values

  // Note: document.getElementById() is used to locate the single DOM

  //       (Document Object Model) element that has the specified

  //       (unique) id attribute specified.

  //------------------------------------------------------------------

  function Compute() {

 

    if ( dataIds.length != perIds.length ) {

      alert( 'Data/percentage fields have different number of elements.' );

    } else {

      var totField = field( totalId );

      

      // gives me the total which is zero right now, why is that?

      // Because we haven't yet assigned the value.

      //alert(totField.value);

     

      var total = 0;

      var count = 0;

 

      //--------------------------------------------------------------

      // Since you are using unique name attributes for the "data"

      // fields, we are using a list of ids to identify each and every

      // data field to be processed.

      // Each element of dataIds is the id attribute of a single data

      // element.

      //--------------------------------------------------------------

      for ( var i = 0; i < dataIds.length; i++ ) {

        var val = field( dataIds[ i ] ).value;

        //alert( 'i: ' + i + ' = "' + dataIds[ i ] + '" => ' + val );  //<-----Angie Test
 

        //------------------------------------------------------------

        // If this field has data, convert the content to its

        // equivalent numeric value, and add this value to the total.

        //------------------------------------------------------------

        if ( val != '' ) {

          total += CurToNum( val );

          count++;

        }

      }

      //--------------------------------------------------------------

      // Assign the "overall total" using the computed sum.

      //--------------------------------------------------------------

      totField.value = formatCurrency( total );

        

      //--------------------------------------------------------------

      // Now, compute each of the associated percentage values

      //--------------------------------------------------------------

      for ( i = 0; i < perIds.length; i++ ) {

        var val = field( dataIds[ i ] ).value;

        //------------------------------------------------------------

        // If this field has data, compute the percentage of the total

        // it represents, and display this in the associated percent

        // field.

        //------------------------------------------------------------

        // Note: If you show too few decimal places for these % output

        //       fields, the sum of the percentage output fields may

        //       not add up to 100%

        //------------------------------------------------------------

        if ( val != '' ) {

          var per = ( CurToNum( val ) * 100 / total );

          field( perIds[ i ] ).value = per.toFixed( 0 );

        }

      }

      field( totalPercentId ).value = '100';

    }

  }

</script>
 
 

        <tr> 

            <td><input type = "text" name = "Expenses" id = "Expenses"  size = "50"  value = "<%=sExpenses%>"  /></td>

            <td align = "right"> <span id="rInputs"> 

              <input type='text' name='POEMoney' id='POEMoney' maxlength = "9"  size = "11"  class='money' onblur='this.value=formatCurrency(this.value); Compute();'   value = "<%=sPOEMoney%>"  />

              </span></td>

            <td align = "right"><span id="rInputs"> 

              <input type = "text"  name = "POEPercentage" id = "POEPercentage" readonly  maxlength = "5" size = "5"   value = "<%=sPOEPercentage%>" />

              </span></td>

          </tr>

          <tr> 

            <td><input type = "text" name = "Land"  id = "Land" value = "<%=sLand%>" size = "50" /></td>

            <td align = "right"><span id="rInputs"> 

              <input type = "text" name = "LandMoney" id = "LandMoney" maxlength = "9"  size = "11"  class="money" onblur='this.value=formatCurrency(this.value); Compute();'   value = "<%=sLandMoney%>" />

              </span></td>

            <td align = "right"><span id="rInputs"> 

              <input type = "text" name = "LandPercentage" id = "LandPercentage" readonly maxlength = "5" size = "5"   value='<%=sLandPercentage%>' />

              </span></td>

          </tr>
 

          <tr> 

            <td><strong>Total Project Costs:

              </td>

            <td align = "right"><span id="rInputs"> 

              <input type = "text" readonly style = "background: #CCCCCC" name = "TotalMoney" id = "TotalMoney" maxlength = "11" size = "14" class="money" onblur="this.value=formatCurrency(this.value);"  value = "<%=sTotalMoney%>" />

              </span></td>

            <td align = "right"><span id="rInputs"> 

              <input type = "text" readonly style = "background: #CCCCCC" name = "TotalPercentage" id = "TotalPercentage"  maxlength = "4" size = "5" value = "<%=sTotalPercentage%>" />

              </span></td>

          </tr>

Open in new window

0
Comment
Question by:Gemini532
  • 2
  • 2
5 Comments
 

Author Comment

by:Gemini532
ID: 20404631
I have no questions, I just wander why when I add zero to the money fields it gives me NAN in the percentage field, zero is still a number, so why the discrepancy??!
0
 
LVL 54

Accepted Solution

by:
b0lsc0tt earned 500 total points
ID: 20408021
The problem in this code was trying to divide by zero.  There are a few ways to fix this but the simplest is with an If.  I have placed it in with you code to see where the problem is and an easy fix.

        // Note: If you show too few decimal places for these % output
        //       fields, the sum of the percentage output fields may
        //       not add up to 100%
        //------------------------------------------------------------
            if (total == 0 ) {
                  alert("Can't do the percentage.");
                  break;
            }
        if ( val != '' ) {            
          var per = ( CurToNum( val ) * 100 / total );
          field( perIds[ i ] ).value = per.toFixed( 0 );

Notice the problem is when total is used as a denominator (bottom part of division).  If the number is 0 then NaN is the result.

Let me know if you have a question or need more help correcting it.

bol
0
 

Author Closing Comment

by:Gemini532
ID: 31412619
GREAT CATCH!! THANK YOU!
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20421773
Your welcome!  I'm glad I could help.  Thanks for another fun question, the grade and the points.

bol
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to dynamically set the form action using jQuery.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now