How can I fix a number value to 2 decimal points in ActionScript 2
?
ActionScript 3
's toFixed() doesn't work for me.
e.g:
1 => 1.00
It turns out it can be achieved with this function:
//format a number into specified number of decimals
function formatDecimals(num, digits) {
//if no decimal places needed, we're done
if (digits <= 0) {
return Math.round(num);
}
//round the number to specified decimals
var tenToPower = Math.pow(10, digits);
var cropped = String(Math.round(num * tenToPower) / tenToPower);
//add decimal point if missing
if (cropped.indexOf(".") == -1) {
cropped += ".0";
}
//finally, force correct number of zeroes; add some if necessary
var halves = cropped.split("."); //grab numbers to the right of the decimal
//compare digits in right half of string to digits wanted
var zerosNeeded = digits - halves[1].length; //number of zeros to add
for (var i=1; i <= zerosNeeded; i++) {
cropped += "0";
}
return(cropped);
}