2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
8 YUI.add('datatype-number-format', function(Y) {
14 * @submodule datatype-number
18 * Format number submodule.
21 * @submodule datatype-number-format
25 * DataType.Number provides a set of utility functions to operate against Number objects.
27 * @class DataType.Number
32 Y.mix(Y.namespace("DataType.Number"), {
34 * Takes a Number and formats to string for display to user.
37 * @param data {Number} Number.
38 * @param config {Object} (Optional) Optional configuration values:
40 * <dt>prefix {String}</dd>
41 * <dd>String prepended before each number, like a currency designator "$"</dd>
42 * <dt>decimalPlaces {Number}</dd>
43 * <dd>Number of decimal places to round. Must be a number 0 to 20.</dd>
44 * <dt>decimalSeparator {String}</dd>
45 * <dd>Decimal separator</dd>
46 * <dt>thousandsSeparator {String}</dd>
47 * <dd>Thousands separator</dd>
48 * <dt>suffix {String}</dd>
49 * <dd>String appended after each number, like " items" (note the space)</dd>
51 * @return {String} Formatted number for display. Note, the following values
52 * return as "": null, undefined, NaN, "".
54 format: function(data, config) {
55 if(LANG.isNumber(data)) {
56 config = config || {};
58 var isNeg = (data < 0),
60 decPlaces = config.decimalPlaces,
61 decSep = config.decimalSeparator || ".",
62 thouSep = config.thousandsSeparator,
67 if(LANG.isNumber(decPlaces) && (decPlaces >= 0) && (decPlaces <= 20)) {
68 // Round to the correct decimal place
69 output = data.toFixed(decPlaces);
74 output = output.replace(".", decSep);
77 // Add the thousands separator
79 // Find the dot or where it would be
80 decIndex = output.lastIndexOf(decSep);
81 decIndex = (decIndex > -1) ? decIndex : output.length;
82 // Start with the dot and everything to the right
83 newOutput = output.substring(decIndex);
84 // Working left, every third time add a separator, every time add a digit
85 for (count = 0, i=decIndex; i>0; i--) {
86 if ((count%3 === 0) && (i !== decIndex) && (!isNeg || (i > 1))) {
87 newOutput = thouSep + newOutput;
89 newOutput = output.charAt(i-1) + newOutput;
96 output = (config.prefix) ? config.prefix + output : output;
99 output = (config.suffix) ? output + config.suffix : output;
103 // Not a Number, just return as string
105 return (LANG.isValue(data) && data.toString) ? data.toString() : "";
111 }, '3.3.0' ,{requires:['yui-base']});