1 /* 2 * (c)2006 Luis Orozco, all rights reserved 3 * version:0.2 4 */ 5 /** 6 * LaoUrl is a collection of math functions. It is intended to provide additional features that the 7 * default Math Object does not have. 8 * This class shouldn't be instantiated 9 * 10 */ 11 class com.innocuo.utils.LaoMath { 12 /** 13 * Round a number to a specific number of decimal places. 14 * <h4>Example</h4> 15 * {@code 16 * var num:Number=LaoMath.round(1.535,1); //returns 1.5 17 * var num2:Number=LaoMath.round(1.535,1,2); //returns 1.50 18 * } 19 * or (if the qdecimal number is negative) aproximate it to the closest group of ten, group of 100, group of 1000, etc 20 * <br/>When qdecimal is less than zero, you'll always end with an integer, therefore, you won't ever see trailing decimal zeros 21 * <h4>Example</h4> 22 * {@code 23 * var num:Number=LaoMath.round(1535.51,-1); //returns 1540 24 * var num2:Number=LaoMath.round(1.51,-1,2); //returns 1540.00 25 * var num2:Number=LaoMath.round(1.51,-2,2); //returns 0.00 26 * } 27 * @param qnum Number to be rounded 28 * @param qdecimal Number of decimal places 29 * @param qdecimalmin [optional] Minimum number of decimal places to display (if necessary, it'll add trailing zeros). <strong>Important:</strong> As it is 30 * the minimum, this parameter will get ignored if qdecimal is greater than qdecimalmin 31 * @return a rounded number to a specific number of decimal places [with optional trailing zeros] 32 */ 33 public static function round(qnum:Number, qdecimal:Number, qdecimalmin:Number):Number { 34 var decimal:Number = Math.pow(10, Math.round(qdecimal)); 35 var num:Number = Math.round(qnum*decimal)/decimal; 36 if (qdecimalmin && qdecimalmin>=qdecimal) { 37 num = LaoMath.formatDecimal(num, qdecimalmin); 38 } 39 return num; 40 } 41 /* adds trailing zeros to a number */ 42 private static function formatDecimal(qnum:Number, qdecimal:Number) { 43 var decimal:Number = Math.round(qdecimal); 44 //if number of decimals is zero, there's no need to continue 45 if (decimal<=0) { 46 return Math.round(qnum); 47 } 48 var newNum:String = String(qnum); 49 //if number is an integer, add a .0 first, so we can continue adding zeros 50 //at least 1 zero is needed 51 if (newNum.indexOf(".") == -1) { 52 newNum += ".0"; 53 } 54 var decimals:String = newNum.split(".")[1]; 55 var zeroMissing = decimal-decimals.length; 56 //add zeros to number 57 for (var i = 1; i<=zeroMissing; i++) { 58 newNum += "0"; 59 } 60 return (newNum); 61 } 62 } 63