all groups > flash (macromedia) > march 2007 >
You're in the

flash (macromedia)

group:

Controlling decimal places


Controlling decimal places KDStudio
3/7/2007 8:07:14 PM
flash (macromedia):


Does any one know if you can control the number of decimal places display when using code to generate dynamic text? I.e. 1.000 instead of 1
Re: Controlling decimal places Pipey
3/7/2007 8:39:39 PM
function formatDecimal(num:Number, decimalPlaces:Number):String{

var strNum:String = String(num);
var zeroesToAdd:Number;

var dotPos = strNum.indexOf(".");
if (dotPos == -1){
strNum = strNum + ".";
zeroesToAdd = decimalPlaces;
} else {
zeroesToAdd = (decimalPlaces + 1) - (strNum.length - dotPos);
}

if (zeroesToAdd < 0){
//remove digits
strNum = strNum.slice(0,strNum.length + zeroesToAdd);
} else {
//add digits
for (var i:Number=0;i<zeroesToAdd;i++){
strNum = strNum + "0";
}
}



return strNum;
}

//examples
trace (formatDecimal(1.25,4));
trace (formatDecimal(162,4));
trace (formatDecimal(1.255,2));
stop();

Note that when reducing the number of decimal places, this function
doesn't round the last digit up - you might want to add that :)

Pipey

[quoted text, click to view]
AddThis Social Bookmark Button