number formatting

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
gurjit
Forum Contributor
Posts: 314
Joined: Thu May 15, 2003 11:53 am
Location: UK

number formatting

Post by gurjit »

hi all,

why does this not work to format the number:


document.form1['tot_apply[]'][thenum].value = document.form1['theamountdue[]'][thenum].value. toFixed(2);


all i want to do is take the number calculated and display it like money (100.00) into the field tot_apply.
User avatar
SystemWisdom
Forum Commoner
Posts: 69
Joined: Sat Mar 26, 2005 5:54 pm
Location: A Canadian South of the 49th Parallel

Post by SystemWisdom »

I wrote these long ago for an E-Comm site, they worked fine for me.. (alternative to 'toFixed')

Example:

Code: Select all

<html>
<head>
<script language=&quote;javascript&quote;><!--
// This ensures users only type float numbers in textboxes
function isFloat( e )
{  var sValidNum = '0123456789.';
   var chCode = (window.Event) ? e.which : e.keyCode;

   if( (chCode == 13) || (chCode == 8) )
      return true;

   if( sValidNum.indexOf( String.fromCharCode( chCode ) ) == -1 )
      return false;
}

// This formats a float into a string with specified decimal places..
function FixFloat( fNum, decPlaces )
{  var i, nDecimal = 1;
   var tNum, nNum, sNum, aNum;

   if( decPlaces == 0 ) return Math.round(fNum);

   for( i = 0; i < decPlaces; i++ )
   {  nDecimal *= 10;
   }

   tNum = Math.round(fNum * nDecimal);
   tNum /= nDecimal;
   nNum = Number(tNum);
   sNum = nNum.toString();
   if( sNum.indexOf(&quote;.&quote;) != -1 )
   {  aNum = sNum.split(&quote;.&quote;);
      if( aNum&#1111;1].length < decPlaces )
      {  sNum = aNum&#1111;0] + &quote;.&quote; + aNum&#1111;1];
         for( i = 0; i < (decPlaces - aNum&#1111;1].length); i++ )
            sNum += &quote;0&quote;;
      }
   }else
   {  sNum += &quote;.&quote;;
      for( i = 0; i < decPlaces; i++ )
         sNum += &quote;0&quote;;
   }

   return sNum;
}


// This is just for example:
function DoSubmit()
{   var frm = document.forms&#1111;0];
    var myFloat = frm.txtBlah.value;

    var myStrFloat = FixFloat( parseFloat(myFloat), 2 );
    
    frm.txtDisplay.value = myStrFloat;

    return;
}
//--></script>
</head>

<body>

<form name=&quote;frmBlah&quote;>

Float-Only: <input type=&quote;text&quote; name=&quote;txtBlah&quote; value=&quote;&quote; onkeypress=&quote;return isFloat(event);&quote;>

<br><br>

<input type=&quote;text&quote; name=&quote;txtDisplay&quote; value=&quote;&quote;>

<input type=&quote;button&quote; value=&quote; Calc &quote; onclick=&quote;DoSubmit()&quote;>

</form>

</body>
</html>
Anyway, I hope that helps!
Post Reply