In AS3, from a division I get a number like this one: 0.9130406010219044. Is there any way to reduce the nu开发者_C百科mber of decimals (aside from multiplying that number for one million)? Is there a way to reduce the numbers BEFORE the division is performed?
Got the following function from this link, which rounds to an arbitrary number of decimals:
public function trim(theNumber:Number, decPlaces:Number) : Number {
if (decPlaces >= 0) {
var temp:Number = Math.pow(10, decPlaces);
return Math.round(theNumber * temp) / temp;
}
return theNumber;
}
// Round a number to two decimal places trace(trim(1.12645, 2));
// Displays: 1.13
Note: I slightly changed the function definition by adding types. See the link for explanation and original source code. Also made it return theNumber
if decPlaces
is less than or equal to zero.
var myNumber:Number = 74.559832;
trace(myNumber.toFixed(4)); //74.5598
trace(myNumber.toFixed(2)); //74.56
AS3 Documentation: Number class
If you just want to display the result (you didn't specify) then a simple bit of String manipulation will yield the fastest result:
0.9130406010219044.toString().substr(0, 4); // 0.91
Take a look at NumberFormatter.fractionalDigits
Or, if you're working in Flex: mx:NumberFormatter.precision / s:NumberFormatter.fractionalDigits
Try some of the answers here on for size:
How to deal with Number precision in Actionscript?
If you use a NumberFormatter, make sure to specify rounding (it's most likely you'll want nearest).
If you need Number as result and performance, I would say this solution is more efficient than the Math.pow() If you need 3 decimals just change 100 by 1000.
var myNumber:Number = 3.553366582;
myNumber = (( myNumber * 100 + 0.5) >> 0) / 100;
//trace = 3.55
demonstrating the rounding :
var myNumber:Number = 3.557366582;
myNumber = (( myNumber * 100 + 0.5) >> 0) / 100;
//trace = 3.56
Regarding the Number.toFixed() returning a String I guess it's because it returns 2 decimals in any case: For instance :
Number(3).toFixed(2); // trace 3.00 so it has to be a String.
精彩评论