1
YUI.add('datatype-number-format', function (Y, NAME) {
4
* The Number Utility provides type-conversion and string-formatting
5
* convenience methods for Numbers.
7
* @module datatype-number
8
* @main datatype-number
12
* Format number submodule.
14
* @module datatype-number
15
* @submodule datatype-number-format
19
* Number provides a set of utility functions to operate against Number objects.
26
Y.mix(Y.namespace("Number"), {
28
* Takes a Number and formats to string for display to user.
31
* @param data {Number} Number.
32
* @param config {Object} (Optional) Optional configuration values:
34
* <dt>prefix {String}</dd>
35
* <dd>String prepended before each number, like a currency designator "$"</dd>
36
* <dt>decimalPlaces {Number}</dd>
37
* <dd>Number of decimal places to round. Must be a number 0 to 20.</dd>
38
* <dt>decimalSeparator {String}</dd>
39
* <dd>Decimal separator</dd>
40
* <dt>thousandsSeparator {String}</dd>
41
* <dd>Thousands separator</dd>
42
* <dt>suffix {String}</dd>
43
* <dd>String appended after each number, like " items" (note the space)</dd>
45
* @return {String} Formatted number for display. Note, the following values
46
* return as "": null, undefined, NaN, "".
48
format: function(data, config) {
49
if(LANG.isNumber(data)) {
50
config = config || {};
52
var isNeg = (data < 0),
54
decPlaces = config.decimalPlaces,
55
decSep = config.decimalSeparator || ".",
56
thouSep = config.thousandsSeparator,
61
if(LANG.isNumber(decPlaces) && (decPlaces >= 0) && (decPlaces <= 20)) {
62
// Round to the correct decimal place
63
output = data.toFixed(decPlaces);
68
output = output.replace(".", decSep);
71
// Add the thousands separator
73
// Find the dot or where it would be
74
decIndex = output.lastIndexOf(decSep);
75
decIndex = (decIndex > -1) ? decIndex : output.length;
76
// Start with the dot and everything to the right
77
newOutput = output.substring(decIndex);
78
// Working left, every third time add a separator, every time add a digit
79
for (count = 0, i=decIndex; i>0; i--) {
80
if ((count%3 === 0) && (i !== decIndex) && (!isNeg || (i > 1))) {
81
newOutput = thouSep + newOutput;
83
newOutput = output.charAt(i-1) + newOutput;
90
output = (config.prefix) ? config.prefix + output : output;
93
output = (config.suffix) ? output + config.suffix : output;
97
// Not a Number, just return as string
99
Y.log("Could not format data from type Number", "warn", "number");
100
return (LANG.isValue(data) && data.toString) ? data.toString() : "";
105
Y.namespace("DataType");
106
Y.DataType.Number = Y.Number;