Truncating a number | Setting the precision of a float | ActionScript 3. AS3

Truncating a Number or Floating Point in ActionScript 3.0 The Efficient Way

I have seen a few solutions for truncating a Number. Many of these solutions used to truncate a float or Number in ActionScript 3.0 (AS3) are just plain over complicated and not optimized. People are often using a technique where they are converting the float into a string and then removing the trailing decimals and then converting it back to a floating point number or the Number type. This works, but is inefficient. I suggest the following for setting the precision of a float:
public static function truncate(val:Number, decimalPlaces:uint):Number{
var multiplier:uint = Math.pow(10, decimalPlaces);
var truncatedVal:Number = val*multiplier;
if (newNumber > int.MAX_VALUE){
return Number(truncatedVal.toFixed(decimalPlaces));
}
return int(truncatedVal)/multiplier;
}
it uses integer operations instead of string operations so it is a fast truncate solution. And when the number is larger than an int it switches to the standard slower way using the toFixed value. I'm sure you could use binary operators to replace the devision inorder to further optimize the function.


comments powered by Disqus