0

如何将数字值固定为 2 个小数点ActionScript 2

ActionScript 3的 toFixed() 对我不起作用。

例如:

1 => 1.00
4

3 回答 3

2

你的函数有一个小错误:如果请求零小数,它返回一个数字,但在所有其他情况下返回一个字符串。这是一个始终返回字符串的版本。它使用打字,这使得很容易找到这种问题:

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);
}
于 2020-11-12T16:06:31.700 回答
1

int()函数中乘以 100 。在int()函数之外 除以 100 。

例如。

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

= 94.7653429602888

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

= 94.76

于 2018-10-09T04:58:17.880 回答
0

事实证明,它可以通过这个功能来实现:

//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);
}
于 2013-08-16T10:10:28.677 回答