1 // ==========================================================================
  2 // Project:   SproutCore - JavaScript Application Framework
  3 // Copyright: ©2006-2011 Strobe Inc. and contributors.
  4 //            Portions ©2008-2011 Apple Inc. All rights reserved.
  5 // License:   Licensed under MIT license (see license.js)
  6 // ==========================================================================
  7 
  8 /**
  9   @class
 10   
 11   Implements some enhancements to the built-in Number object that makes it
 12   easier to handle rounding and display of numbers.
 13   
 14   @since SproutCore 1.0
 15   @author Colin Campbell
 16 */
 17 SC.Math = SC.Object.create(
 18 /** @lends SC.Math.prototype */ {
 19   
 20   /**
 21     Checks to see if the number is near the supplied parameter to a certain lambda.
 22     
 23     @param {Number} n1 First number in comparison.
 24     @param {Number} n2 Number to compare against the first.
 25     @param {Number} lambda The closeness sufficient for a positive result. Default 0.00001
 26     @returns {Boolean}
 27   */
 28   near: function(n1, n2, lambda) {
 29     if (!lambda) lambda = 0.00001;
 30     return Math.abs(n1 - n2) <= lambda;
 31   },
 32   
 33   /**
 34     Rounds a number to a given decimal place. If a negative decimalPlace
 35     parameter is provided, the number will be rounded outward (ie. providing
 36     -3 will round to the thousands).
 37     
 38     Function is insufficient for high negative values of decimalPlace parameter.
 39     For example, (123456.789).round(-5) should evaluate to 100000 but instead
 40     evaluates to 99999.999... 
 41     
 42     @param {Number} n The number to round
 43     @param {Integer} decimalPlace
 44     @returns {Number}
 45   */
 46   round: function(n, decimalPlace) {
 47     if (!decimalPlace) decimalPlace = 0;
 48     var factor = Math.pow(10, decimalPlace);
 49     if (decimalPlace < 0) {
 50        // stop rounding errors from hurting the factor...
 51       var s = factor.toString();
 52       factor = s.substring(0, s.indexOf("1")+1);
 53     }
 54     n = n.valueOf();
 55     return Math.round(n * factor) / factor;
 56   }
 57   
 58 }) ;
 59