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

Published by Nicholas Dunbar on December 27th, 2012

# 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;

}