Question

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
Was it helpful?

Solution 3

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);
}

OTHER TIPS

There is a slight error in your function: It returns a Number if zero decimals are requested, but a String in all other cases. Here is a version that always returns a String. It uses typing, which makes it easy to find that kind of problem:

function formatDecimals(num: Number, decimal_places: int): String {
    //if no decimal places needed, we're done
    if (decimal_places <= 0) {
        return Math.round(num).toString();
    }
    //round the number to specified decimals
    var tenToPower: int = Math.pow(10, decimal_places);
    var cropped: String = 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: Array = cropped.split("."); //grab numbers to the right of the decimal
    //compare decimal_places in right half of string to decimal_places wanted
    var zerosNeeded: int = decimal_places - halves[1].length; //number of zeros to add
    for (var i = 1; i <= zerosNeeded; i++) {
        cropped += "0";
    }
    return (cropped);
}

Multiply by 100 inside int() function. Divide by 100 outside int() function.

eg.

on (release) {
    myValue = 10500/110.8;
}

= 94.7653429602888

on (release) {
    myValue = int((10500/110.8)*100)/100;
}

= 94.76

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top