Brian Chia
       
 
categories
actionscript
actionscript 1.0
actionscript 2.0
misc
 
processing
 
links
brian chia
kelvin zhao
ronald leong
 
 
Format Number
 
A simple function to return an expression formatted as a number rounded off to the specified number of decimal places.

In fact, in PHP and ASP there is standard bulit in function, number_format & FormatNumber to perform this, but there seem to be none in Flash. Thus, i decided to write one and call it formatNum.

In my formatNum, you will need to pass 2 variables in:
i) the value to be formatted, in either string or number variables
ii) number of decimal places to be formatted



function formatNum(a:Object,dp:Number):Number{ // declare object will be able to handle string & number

// multiple amount by 10 to the power of dp & convert to string format
var amount:String=String(Math.round(a*Math.pow(10,dp)));
var decimal:String=amount.slice(-dp);
var integer:String=amount.substring(0,amount.length-dp);

// return a number variable
return parseFloat(integer+"."+decimal);

}

trace(formatNum(123.45678,2)); // output:123.46
trace(formatNum("123.45678",3)); // output:123.457
trace(formatNum(123.45678,2)+formatNum("123.45678",3)); // output:246.917



suggestion

 
 
 
         
  © copyright 2007 THINKLUNATIC.    
Brian Chia Jonathan Ng