[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 369
  • Last Modified:

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

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
Gemini532
Asked:
Gemini532
  • 2
  • 2
1 Solution
 
Gemini532Author Commented:
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
 
b0lsc0ttIT ManagerCommented:
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
 
Gemini532Author Commented:
GREAT CATCH!! THANK YOU!
0
 
b0lsc0ttIT ManagerCommented:
Your welcome!  I'm glad I could help.  Thanks for another fun question, the grade and the points.

bol
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now