3
Copyright 2012 Yahoo! Inc. All rights reserved.
4
Licensed under the BSD License.
5
http://yuilibrary.com/license/
7
YUI.add('datatype-number-format', function(Y) {
13
* @submodule datatype-number
17
* Format number submodule.
20
* @submodule datatype-number-format
24
* DataType.Number provides a set of utility functions to operate against Number objects.
26
* @class DataType.Number
31
Y.mix(Y.namespace("DataType.Number"), {
33
* Takes a Number and formats to string for display to user.
36
* @param data {Number} Number.
37
* @param config {Object} (Optional) Optional configuration values:
39
* <dt>prefix {HTML}</dd>
40
* <dd>String prepended before each number, like a currency designator "$"</dd>
41
* <dt>decimalPlaces {Number}</dd>
42
* <dd>Number of decimal places to round. Must be a number 0 to 20.</dd>
43
* <dt>decimalSeparator {HTML}</dd>
44
* <dd>Decimal separator</dd>
45
* <dt>thousandsSeparator {HTML}</dd>
46
* <dd>Thousands separator</dd>
47
* <dt>suffix {HTML}</dd>
48
* <dd>String appended after each number, like " items" (note the space)</dd>
50
* @return {HTML} Formatted number for display. Note, the following values
51
* return as "": null, undefined, NaN, "".
53
format: function(data, config) {
54
if(LANG.isNumber(data)) {
55
config = config || {};
57
var isNeg = (data < 0),
59
decPlaces = config.decimalPlaces,
60
decSep = config.decimalSeparator || ".",
61
thouSep = config.thousandsSeparator,
66
if(LANG.isNumber(decPlaces) && (decPlaces >= 0) && (decPlaces <= 20)) {
67
// Round to the correct decimal place
68
output = data.toFixed(decPlaces);
73
output = output.replace(".", decSep);
76
// Add the thousands separator
78
// Find the dot or where it would be
79
decIndex = output.lastIndexOf(decSep);
80
decIndex = (decIndex > -1) ? decIndex : output.length;
81
// Start with the dot and everything to the right
82
newOutput = output.substring(decIndex);
83
// Working left, every third time add a separator, every time add a digit
84
for (count = 0, i=decIndex; i>0; i--) {
85
if ((count%3 === 0) && (i !== decIndex) && (!isNeg || (i > 1))) {
86
newOutput = thouSep + newOutput;
88
newOutput = output.charAt(i-1) + newOutput;
95
output = (config.prefix) ? config.prefix + output : output;
98
output = (config.suffix) ? output + config.suffix : output;
102
// Not a Number, just return as string
104
return (LANG.isValue(data) && data.toString) ? data.toString() : "";