2 YUI 3.13.0 (build 508226d)
3 Copyright 2013 Yahoo! Inc. All rights reserved.
4 Licensed under the BSD License.
5 http://yuilibrary.com/license/
8 YUI.add('datatype-number-format', function (Y, NAME) {
11 * The Number Utility provides type-conversion and string-formatting
12 * convenience methods for Numbers.
14 * @module datatype-number
15 * @main datatype-number
19 * Format number submodule.
21 * @module datatype-number
22 * @submodule datatype-number-format
26 * Number provides a set of utility functions to operate against Number objects.
33 Y.mix(Y.namespace("Number"), {
35 * Takes a Number and formats to string for display to user.
38 * @param data {Number} Number.
39 * @param config {Object} (Optional) Optional configuration values:
41 * <dt>prefix {HTML}</dd>
42 * <dd>String prepended before each number, like a currency designator "$"</dd>
43 * <dt>decimalPlaces {Number}</dd>
44 * <dd>Number of decimal places to round. Must be a number 0 to 20.</dd>
45 * <dt>decimalSeparator {HTML}</dd>
46 * <dd>Decimal separator</dd>
47 * <dt>thousandsSeparator {HTML}</dd>
48 * <dd>Thousands separator</dd>
49 * <dt>suffix {HTML}</dd>
50 * <dd>String appended after each number, like " items" (note the space)</dd>
52 * @return {HTML} Formatted number for display. Note, the following values
53 * return as "": null, undefined, NaN, "".
55 format: function(data, config) {
56 if(LANG.isNumber(data)) {
57 config = config || {};
59 var isNeg = (data < 0),
61 decPlaces = config.decimalPlaces,
62 decSep = config.decimalSeparator || ".",
63 thouSep = config.thousandsSeparator,
68 if(LANG.isNumber(decPlaces) && (decPlaces >= 0) && (decPlaces <= 20)) {
69 // Round to the correct decimal place
70 output = data.toFixed(decPlaces);
75 output = output.replace(".", decSep);
78 // Add the thousands separator
80 // Find the dot or where it would be
81 decIndex = output.lastIndexOf(decSep);
82 decIndex = (decIndex > -1) ? decIndex : output.length;
83 // Start with the dot and everything to the right
84 newOutput = output.substring(decIndex);
85 // Working left, every third time add a separator, every time add a digit
86 for (count = 0, i=decIndex; i>0; i--) {
87 if ((count%3 === 0) && (i !== decIndex) && (!isNeg || (i > 1))) {
88 newOutput = thouSep + newOutput;
90 newOutput = output.charAt(i-1) + newOutput;
97 output = (config.prefix) ? config.prefix + output : output;
100 output = (config.suffix) ? output + config.suffix : output;
104 // Not a Number, just return as string
106 return (LANG.isValue(data) && data.toString) ? data.toString() : "";
111 Y.namespace("DataType");
112 Y.DataType.Number = Y.Number;