Coding Tips (JavaScript/CSS/VBA/Win32)

Useful code snippets, tips and some Windows applications

A JavaScript number format function

Here is a Javascript script to format a number with a number of decimal places from 0 to 3. It is based on another function to format a currency I found on the World Wild Web. If you wish to increase the number of decimal places, just add case labels to the switch statement.

 function formatNumber (obj, decimal) {
	 //decimal  - the number of decimals after the digit from 0 to 3
//-- Returns the passed number as a string in the xxx,xxx.xx format.
	   anynum=eval(obj.value);
	   divider =10;
	   switch(decimal){
			case 0:
				divider =1;
				break;
			case 1:
				divider =10;
				break;
			case 2:
				divider =100;
				break;
			default:  	 //for 3 decimal places
				divider =1000;
		}

	   workNum=Math.abs((Math.round(anynum*divider)/divider));

	   workStr=""+workNum

	   if (workStr.indexOf(".")==-1){workStr+="."}

	   dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
	   pStr=workStr.substr(workStr.indexOf("."))

	   while (pStr.length-1< decimal){pStr+="0"}

	   if(pStr =='.') pStr ='';

	   //--- Adds a comma in the thousands place.    
	   if (dNum>=1000) {
		  dLen=dStr.length
		  dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
	   }

	   //-- Adds a comma in the millions place.
	   if (dNum>=1000000) {
		  dLen=dStr.length
		  dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
	   }
	   retval = dStr + pStr
	   //-- Put numbers in parentheses if negative.
	   if (anynum<0) {retval="("+retval+")";}

	  
	//You could include a dollar sign in the return value.
	  //retval =  "$"+retval
	  
	  obj.value = retval;
 }

Usage: Usage: <input type=text onChange='formatNumber(this,2)'>

Try it: Enter a number and tab out.

A JavaScript function to remove a cents portion from a number.

This Javascript function removes a cents portion from a number and automatically adds ".00" to the number.

 function removeCents(obj){
	val = obj.value;
	pos = val.indexOf(".");

	if(pos>-1)
		str= val.substr(0,val.indexOf("."));
	else
		str =val;
	obj.value = str+".00";
 }
Usage: <input type=text onChange='removeCents(this)'>

Try it: Enter a number and tab out.


More JavaScript tips at http://www.ekcsoft.com/coding/js/

Questions or comments?