Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2007-12-04
5
Medium Priority
?
366 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL several years ago, it seemed like now was a good time to update it for object-oriented PHP.  This article does that, replacing as much as possible the pr…
SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

715 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