Format.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /***
  2. MochiKit.Format 1.4
  3. See <http://mochikit.com/> for documentation, downloads, license, etc.
  4. (c) 2005 Bob Ippolito. All rights Reserved.
  5. ***/
  6. if (typeof(dojo) != 'undefined') {
  7. dojo.provide('MochiKit.Format');
  8. }
  9. if (typeof(MochiKit) == 'undefined') {
  10. MochiKit = {};
  11. }
  12. if (typeof(MochiKit.Format) == 'undefined') {
  13. MochiKit.Format = {};
  14. }
  15. MochiKit.Format.NAME = "MochiKit.Format";
  16. MochiKit.Format.VERSION = "1.4";
  17. MochiKit.Format.__repr__ = function () {
  18. return "[" + this.NAME + " " + this.VERSION + "]";
  19. };
  20. MochiKit.Format.toString = function () {
  21. return this.__repr__();
  22. };
  23. MochiKit.Format._numberFormatter = function (placeholder, header, footer, locale, isPercent, precision, leadingZeros, separatorAt, trailingZeros) {
  24. return function (num) {
  25. num = parseFloat(num);
  26. if (typeof(num) == "undefined" || num === null || isNaN(num)) {
  27. return placeholder;
  28. }
  29. var curheader = header;
  30. var curfooter = footer;
  31. if (num < 0) {
  32. num = -num;
  33. } else {
  34. curheader = curheader.replace(/-/, "");
  35. }
  36. var me = arguments.callee;
  37. var fmt = MochiKit.Format.formatLocale(locale);
  38. if (isPercent) {
  39. num = num * 100.0;
  40. curfooter = fmt.percent + curfooter;
  41. }
  42. num = MochiKit.Format.roundToFixed(num, precision);
  43. var parts = num.split(/\./);
  44. var whole = parts[0];
  45. var frac = (parts.length == 1) ? "" : parts[1];
  46. var res = "";
  47. while (whole.length < leadingZeros) {
  48. whole = "0" + whole;
  49. }
  50. if (separatorAt) {
  51. while (whole.length > separatorAt) {
  52. var i = whole.length - separatorAt;
  53. //res = res + fmt.separator + whole.substring(i, whole.length);
  54. res = fmt.separator + whole.substring(i, whole.length) + res;
  55. whole = whole.substring(0, i);
  56. }
  57. }
  58. res = whole + res;
  59. if (precision > 0) {
  60. while (frac.length < trailingZeros) {
  61. frac = frac + "0";
  62. }
  63. res = res + fmt.decimal + frac;
  64. }
  65. return curheader + res + curfooter;
  66. };
  67. };
  68. /** @id MochiKit.Format.numberFormatter */
  69. MochiKit.Format.numberFormatter = function (pattern, placeholder/* = "" */, locale/* = "default" */) {
  70. // http://java.sun.com/docs/books/tutorial/i18n/format/numberpattern.html
  71. // | 0 | leading or trailing zeros
  72. // | # | just the number
  73. // | , | separator
  74. // | . | decimal separator
  75. // | % | Multiply by 100 and format as percent
  76. if (typeof(placeholder) == "undefined") {
  77. placeholder = "";
  78. }
  79. var match = pattern.match(/((?:[0#]+,)?[0#]+)(?:\.([0#]+))?(%)?/);
  80. if (!match) {
  81. throw TypeError("Invalid pattern");
  82. }
  83. var header = pattern.substr(0, match.index);
  84. var footer = pattern.substr(match.index + match[0].length);
  85. if (header.search(/-/) == -1) {
  86. header = header + "-";
  87. }
  88. var whole = match[1];
  89. var frac = (typeof(match[2]) == "string" && match[2] != "") ? match[2] : "";
  90. var isPercent = (typeof(match[3]) == "string" && match[3] != "");
  91. var tmp = whole.split(/,/);
  92. var separatorAt;
  93. if (typeof(locale) == "undefined") {
  94. locale = "default";
  95. }
  96. if (tmp.length == 1) {
  97. separatorAt = null;
  98. } else {
  99. separatorAt = tmp[1].length;
  100. }
  101. var leadingZeros = whole.length - whole.replace(/0/g, "").length;
  102. var trailingZeros = frac.length - frac.replace(/0/g, "").length;
  103. var precision = frac.length;
  104. var rval = MochiKit.Format._numberFormatter(
  105. placeholder, header, footer, locale, isPercent, precision,
  106. leadingZeros, separatorAt, trailingZeros
  107. );
  108. var m = MochiKit.Base;
  109. if (m) {
  110. var fn = arguments.callee;
  111. var args = m.concat(arguments);
  112. rval.repr = function () {
  113. return [
  114. self.NAME,
  115. "(",
  116. map(m.repr, args).join(", "),
  117. ")"
  118. ].join("");
  119. };
  120. }
  121. return rval;
  122. };
  123. /** @id MochiKit.Format.formatLocale */
  124. MochiKit.Format.formatLocale = function (locale) {
  125. if (typeof(locale) == "undefined" || locale === null) {
  126. locale = "default";
  127. }
  128. if (typeof(locale) == "string") {
  129. var rval = MochiKit.Format.LOCALE[locale];
  130. if (typeof(rval) == "string") {
  131. rval = arguments.callee(rval);
  132. MochiKit.Format.LOCALE[locale] = rval;
  133. }
  134. return rval;
  135. } else {
  136. return locale;
  137. }
  138. };
  139. /** @id MochiKit.Format.twoDigitAverage */
  140. MochiKit.Format.twoDigitAverage = function (numerator, denominator) {
  141. if (denominator) {
  142. var res = numerator / denominator;
  143. if (!isNaN(res)) {
  144. return MochiKit.Format.twoDigitFloat(numerator / denominator);
  145. }
  146. }
  147. return "0";
  148. };
  149. /** @id MochiKit.Format.twoDigitFloat */
  150. MochiKit.Format.twoDigitFloat = function (someFloat) {
  151. var sign = (someFloat < 0 ? '-' : '');
  152. var s = Math.floor(Math.abs(someFloat) * 100).toString();
  153. if (s == '0') {
  154. return s;
  155. }
  156. if (s.length < 3) {
  157. while (s.charAt(s.length - 1) == '0') {
  158. s = s.substring(0, s.length - 1);
  159. }
  160. return sign + '0.' + s;
  161. }
  162. var head = sign + s.substring(0, s.length - 2);
  163. var tail = s.substring(s.length - 2, s.length);
  164. if (tail == '00') {
  165. return head;
  166. } else if (tail.charAt(1) == '0') {
  167. return head + '.' + tail.charAt(0);
  168. } else {
  169. return head + '.' + tail;
  170. }
  171. };
  172. /** @id MochiKit.Format.lstrip */
  173. MochiKit.Format.lstrip = function (str, /* optional */chars) {
  174. str = str + "";
  175. if (typeof(str) != "string") {
  176. return null;
  177. }
  178. if (!chars) {
  179. return str.replace(/^\s+/, "");
  180. } else {
  181. return str.replace(new RegExp("^[" + chars + "]+"), "");
  182. }
  183. };
  184. /** @id MochiKit.Format.rstrip */
  185. MochiKit.Format.rstrip = function (str, /* optional */chars) {
  186. str = str + "";
  187. if (typeof(str) != "string") {
  188. return null;
  189. }
  190. if (!chars) {
  191. return str.replace(/\s+$/, "");
  192. } else {
  193. return str.replace(new RegExp("[" + chars + "]+$"), "");
  194. }
  195. };
  196. /** @id MochiKit.Format.strip */
  197. MochiKit.Format.strip = function (str, /* optional */chars) {
  198. var self = MochiKit.Format;
  199. return self.rstrip(self.lstrip(str, chars), chars);
  200. };
  201. /** @id MochiKit.Format.truncToFixed */
  202. MochiKit.Format.truncToFixed = function (aNumber, precision) {
  203. aNumber = Math.floor(aNumber * Math.pow(10, precision));
  204. var res = (aNumber * Math.pow(10, -precision)).toFixed(precision);
  205. if (res.charAt(0) == ".") {
  206. res = "0" + res;
  207. }
  208. return res;
  209. };
  210. /** @id MochiKit.Format.roundToFixed */
  211. MochiKit.Format.roundToFixed = function (aNumber, precision) {
  212. return MochiKit.Format.truncToFixed(
  213. aNumber + 0.5 * Math.pow(10, -precision),
  214. precision
  215. );
  216. };
  217. /** @id MochiKit.Format.percentFormat */
  218. MochiKit.Format.percentFormat = function (someFloat) {
  219. return MochiKit.Format.twoDigitFloat(100 * someFloat) + '%';
  220. };
  221. MochiKit.Format.EXPORT = [
  222. "truncToFixed",
  223. "roundToFixed",
  224. "numberFormatter",
  225. "formatLocale",
  226. "twoDigitAverage",
  227. "twoDigitFloat",
  228. "percentFormat",
  229. "lstrip",
  230. "rstrip",
  231. "strip"
  232. ];
  233. MochiKit.Format.LOCALE = {
  234. en_US: {separator: ",", decimal: ".", percent: "%"},
  235. de_DE: {separator: ".", decimal: ",", percent: "%"},
  236. fr_FR: {separator: " ", decimal: ",", percent: "%"},
  237. "default": "en_US"
  238. };
  239. MochiKit.Format.EXPORT_OK = [];
  240. MochiKit.Format.EXPORT_TAGS = {
  241. ':all': MochiKit.Format.EXPORT,
  242. ':common': MochiKit.Format.EXPORT
  243. };
  244. MochiKit.Format.__new__ = function () {
  245. // MochiKit.Base.nameFunctions(this);
  246. var base = this.NAME + ".";
  247. var k, v, o;
  248. for (k in this.LOCALE) {
  249. o = this.LOCALE[k];
  250. if (typeof(o) == "object") {
  251. o.repr = function () { return this.NAME; };
  252. o.NAME = base + "LOCALE." + k;
  253. }
  254. }
  255. for (k in this) {
  256. o = this[k];
  257. if (typeof(o) == 'function' && typeof(o.NAME) == 'undefined') {
  258. try {
  259. o.NAME = base + k;
  260. } catch (e) {
  261. // pass
  262. }
  263. }
  264. }
  265. };
  266. MochiKit.Format.__new__();
  267. if (typeof(MochiKit.Base) != "undefined") {
  268. MochiKit.Base._exportSymbols(this, MochiKit.Format);
  269. } else {
  270. (function (globals, module) {
  271. if ((typeof(JSAN) == 'undefined' && typeof(dojo) == 'undefined')
  272. || (MochiKit.__export__ === false)) {
  273. var all = module.EXPORT_TAGS[":all"];
  274. for (var i = 0; i < all.length; i++) {
  275. globals[all[i]] = module[all[i]];
  276. }
  277. }
  278. })(this, MochiKit.Format);
  279. }