-
Notifications
You must be signed in to change notification settings - Fork 3
/
NumberStrings.js
108 lines (108 loc) · 3.37 KB
/
NumberStrings.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* Name: NumberStrings.js
* Author: Jamie Street
* Website: http://jamie.st
*/
var NumberStrings = (function () {
function NumberStrings(options) {
this.options = options;
// Declare the default options
var default_options = {
units: [
{
name: 'hundred',
value: 100
},
{
name: 'thousand',
value: 1000
},
{
name: 'million',
value: 1000000
},
{
name: 'billion',
value: 1000000000
},
{
name: 'trillion',
value: 1000000000000
},
{
name: 'quadrillion',
value: 1000000000000000
},
{
name: 'quintillion',
value: 1000000000000000000
},
{
name: 'sextillion',
value: 1000000000000000000000
},
{
name: 'septillion',
value: 1000000000000000000000000
}
]
};
// Iterate through and decide if we're using the default or the users input
this.options = options || {};
for (var opt in default_options) {
if (default_options.hasOwnProperty(opt) && !this.options.hasOwnProperty(opt)) {
this.options[opt] = default_options[opt];
}
}
// Put units in their own variable, just to make later code a little more readable
this.units = this.options.units;
}
// Returns the appropriate unit object, depending on the number provided
NumberStrings.prototype.getUnit = function (number) {
var unit = null;
for (var i = 0; i < this.units.length; i++) {
if (number < this.units[i].value) {
break;
}
if (number >= this.units[i].value) {
unit = this.units[i];
}
}
return unit;
};
// Returns the name of the unit that is most appropriate for the number provided
NumberStrings.prototype.getName = function (number) {
var unit = this.getUnit(number);
if (unit) {
return unit.name;
}
else {
return null;
}
};
// Returns the "decimal" (for lack of a better word) that goes in front of the
// unit name, for the number provided
NumberStrings.prototype.getDecimal = function (number) {
var unit = this.getUnit(number);
if (unit) {
return parseFloat(number / unit.value);
}
else {
return number;
}
};
// Returns a string in the format of: {{decimal}} {{unitname}}, for the number provided
NumberStrings.prototype.format = function (number) {
var unit = this.getUnit(number);
if (unit) {
return this.getDecimal(number) + ' ' + this.getName(number);
}
else {
return number;
}
};
return NumberStrings;
})();
if (typeof exports !== 'undefined' && this.exports !== exports) {
module.exports = NumberStrings;
}