prefer larger codes for MGT
[roojs1] / Roo / util / Format.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12 /**
13  * @class Roo.util.Format
14  * Reusable data formatting functions
15  * @singleton
16  */
17 Roo.util.Format = function(){
18     var trimRe = /^\s+|\s+$/g;
19     return {
20         /**
21          * Truncate a string and add an ellipsis ('...') to the end if it exceeds the specified length
22          * @param {String} value The string to truncate
23          * @param {Number} length The maximum length to allow before truncating
24          * @return {String} The converted text
25          */
26         ellipsis : function(value, len){
27             if(value && value.length > len){
28                 return value.substr(0, len-3)+"...";
29             }
30             return value;
31         },
32
33         /**
34          * Checks a reference and converts it to empty string if it is undefined
35          * @param {Mixed} value Reference to check
36          * @return {Mixed} Empty string if converted, otherwise the original value
37          */
38         undef : function(value){
39             return typeof value != "undefined" ? value : "";
40         },
41
42         /**
43          * Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.
44          * @param {String} value The string to encode
45          * @return {String} The encoded text
46          */
47         htmlEncode : function(value){
48             return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
49         },
50
51         /**
52          * Convert certain characters (&, <, >, and ') from their HTML character equivalents.
53          * @param {String} value The string to decode
54          * @return {String} The decoded text
55          */
56         htmlDecode : function(value){
57             return !value ? value : String(value).replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"');
58         },
59
60         /**
61          * Trims any whitespace from either side of a string
62          * @param {String} value The text to trim
63          * @return {String} The trimmed text
64          */
65         trim : function(value){
66             return String(value).replace(trimRe, "");
67         },
68
69         /**
70          * Returns a substring from within an original string
71          * @param {String} value The original text
72          * @param {Number} start The start index of the substring
73          * @param {Number} length The length of the substring
74          * @return {String} The substring
75          */
76         substr : function(value, start, length){
77             return String(value).substr(start, length);
78         },
79
80         /**
81          * Converts a string to all lower case letters
82          * @param {String} value The text to convert
83          * @return {String} The converted text
84          */
85         lowercase : function(value){
86             return String(value).toLowerCase();
87         },
88
89         /**
90          * Converts a string to all upper case letters
91          * @param {String} value The text to convert
92          * @return {String} The converted text
93          */
94         uppercase : function(value){
95             return String(value).toUpperCase();
96         },
97
98         /**
99          * Converts the first character only of a string to upper case
100          * @param {String} value The text to convert
101          * @return {String} The converted text
102          */
103         capitalize : function(value){
104             return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
105         },
106
107         // private
108         call : function(value, fn){
109             if(arguments.length > 2){
110                 var args = Array.prototype.slice.call(arguments, 2);
111                 args.unshift(value);
112                  
113                 return /** eval:var:value */  eval(fn).apply(window, args);
114             }else{
115                 /** eval:var:value */
116                 return /** eval:var:value */ eval(fn).call(window, value);
117             }
118         },
119
120        
121         /**
122          * safer version of Math.toFixed..??/
123          * @param {Number/String} value The numeric value to format
124          * @param {Number/String} value Decimal places 
125          * @return {String} The formatted currency string
126          */
127         toFixed : function(v, n)
128         {
129             // why not use to fixed - precision is buggered???
130             if (!n) {
131                 return Math.round(v-0);
132             }
133             var fact = Math.pow(10,n+1);
134             v = (Math.round((v-0)*fact))/fact;
135             var z = (''+fact).substring(2);
136             if (v == Math.floor(v)) {
137                 return Math.floor(v) + '.' + z;
138             }
139             
140             // now just padd decimals..
141             var ps = String(v).split('.');
142             var fd = (ps[1] + z);
143             var r = fd.substring(0,n); 
144             var rm = fd.substring(n); 
145             if (rm < 5) {
146                 return ps[0] + '.' + r;
147             }
148             r*=1; // turn it into a number;
149             r++;
150             if (String(r).length != n) {
151                 ps[0]*=1;
152                 ps[0]++;
153                 r = String(r).substring(1); // chop the end off.
154             }
155             
156             return ps[0] + '.' + r;
157              
158         },
159         
160         /**
161          * Format a number as US currency
162          * @param {Number/String} value The numeric value to format
163          * @return {String} The formatted currency string
164          */
165         usMoney : function(v){
166             return '$' + Roo.util.Format.number(v);
167         },
168         
169         /**
170          * Format a number
171          * eventually this should probably emulate php's number_format
172          * @param {Number/String} value The numeric value to format
173          * @param {Number} decimals number of decimal places
174          * @param {String} delimiter for thousands (default comma)
175          * @return {String} The formatted currency string
176          */
177         number : function(v, decimals, thousandsDelimiter)
178         {
179             // multiply and round.
180             decimals = typeof(decimals) == 'undefined' ? 2 : decimals;
181             thousandsDelimiter = typeof(thousandsDelimiter) == 'undefined' ? ',' : thousandsDelimiter;
182             
183             var mul = Math.pow(10, decimals);
184             var zero = String(mul).substring(1);
185             v = (Math.round((v-0)*mul))/mul;
186             
187             // if it's '0' number.. then
188             
189             //v = (v == Math.floor(v)) ? v + "." + zero : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
190             v = String(v);
191             var ps = v.split('.');
192             var whole = ps[0];
193             
194             var r = /(\d+)(\d{3})/;
195             // add comma's
196             
197             if(thousandsDelimiter.length != 0) {
198                 whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, thousandsDelimiter );
199             } 
200             
201             var sub = ps[1] ?
202                     // has decimals..
203                     (decimals ?  ('.'+ ps[1] + zero.substring(ps[1].length)) : '') :
204                     // does not have decimals
205                     (decimals ? ('.' + zero) : '');
206             
207             
208             return whole + sub ;
209         },
210         
211         /**
212          * Parse a value into a formatted date using the specified format pattern.
213          * @param {Mixed} value The value to format
214          * @param {String} format (optional) Any valid date format string (defaults to 'm/d/Y')
215          * @return {String} The formatted date string
216          */
217         date : function(v, format){
218             if(!v){
219                 return "";
220             }
221             if(!(v instanceof Date)){
222                 v = new Date(Date.parse(v));
223             }
224             return v.dateFormat(format || Roo.util.Format.defaults.date);
225         },
226
227         /**
228          * Returns a date rendering function that can be reused to apply a date format multiple times efficiently
229          * @param {String} format Any valid date format string
230          * @return {Function} The date formatting function
231          */
232         dateRenderer : function(format){
233             return function(v){
234                 return Roo.util.Format.date(v, format);  
235             };
236         },
237
238         // private
239         stripTagsRE : /<\/?[^>]+>/gi,
240         
241         /**
242          * Strips all HTML tags
243          * @param {Mixed} value The text from which to strip tags
244          * @return {String} The stripped text
245          */
246         stripTags : function(v){
247             return !v ? v : String(v).replace(this.stripTagsRE, "");
248         },
249         
250         /**
251          * Size in Mb,Gb etc.
252          * @param {Number} value The number to be formated
253          * @param {number} decimals how many decimal places
254          * @return {String} the formated string
255          */
256         size : function(value, decimals)
257         {
258             var sizes = ['b', 'k', 'M', 'G', 'T'];
259             if (value == 0) {
260                 return 0;
261             }
262             var i = parseInt(Math.floor(Math.log(value) / Math.log(1024)));
263             return Roo.util.Format.number(value/ Math.pow(1024, i) ,decimals)   + sizes[i];
264         }
265         
266         
267         
268     };
269 }();
270 Roo.util.Format.defaults = {
271     date : 'd/M/Y'
272 };