Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / core / src / lang / Number.js
1 /**
2  * @class Ext.Number
3  *
4  * A collection of useful static methods to deal with numbers
5  * @singleton
6  */
7
8 (function() {
9
10 var isToFixedBroken = (0.9).toFixed() !== '1';
11
12 Ext.Number = {
13     /**
14      * Checks whether or not the current number is within a desired range.  If the number is already within the
15      * range it is returned, otherwise the min or max value is returned depending on which side of the range is
16      * exceeded. Note that this method returns the constrained value but does not change the current number.
17      * @param {Number} number The number to check
18      * @param {Number} min The minimum number in the range
19      * @param {Number} max The maximum number in the range
20      * @return {Number} The constrained value if outside the range, otherwise the current value
21      */
22     constrain: function(number, min, max) {
23         number = parseFloat(number);
24
25         if (!isNaN(min)) {
26             number = Math.max(number, min);
27         }
28         if (!isNaN(max)) {
29             number = Math.min(number, max);
30         }
31         return number;
32     },
33
34     /**
35      * Formats a number using fixed-point notation
36      * @param {Number} value The number to format
37      * @param {Number} precision The number of digits to show after the decimal point
38      */
39     toFixed: function(value, precision) {
40         if (isToFixedBroken) {
41             precision = precision || 0;
42             var pow = Math.pow(10, precision);
43             return (Math.round(value * pow) / pow).toFixed(precision);
44         }
45
46         return value.toFixed(precision);
47     },
48
49     /**
50      * Validate that a value is numeric and convert it to a number if necessary. Returns the specified default value if
51      * it is not.
52
53 Ext.Number.from('1.23', 1); // returns 1.23
54 Ext.Number.from('abc', 1); // returns 1
55
56      * @param {Mixed} value
57      * @param {Number} defaultValue The value to return if the original value is non-numeric
58      * @return {Number} value, if numeric, defaultValue otherwise
59      */
60     from: function(value, defaultValue) {
61         if (isFinite(value)) {
62             value = parseFloat(value);
63         }
64
65         return !isNaN(value) ? value : defaultValue;
66     }
67 };
68
69 })();
70
71 /**
72  * This method is deprecated, please use {@link Ext.Number#from Ext.Number.from} instead
73  *
74  * @deprecated 4.0.0 Replaced by Ext.Number.from
75  * @member Ext
76  * @method num
77  */
78 Ext.num = function() {
79     return Ext.Number.from.apply(this, arguments);
80 };