Solved

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

Posted on 2007-12-04
5
356 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
Comment Utility
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
Comment Utility
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
Comment Utility
GREAT CATCH!! THANK YOU!
0
 
LVL 54

Expert Comment

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

bol
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

763 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

6 Experts available now in Live!

Get 1:1 Help Now