forked from domharrington/js-number-abbreviate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (33 loc) · 1.13 KB
/
index.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
(function(root){
'use strict';
function NumberAbbreviate(abbrev) {
if (!(this instanceof NumberAbbreviate)) return new NumberAbbreviate(abbrev)
this.abbrev = abbrev == null ? ['k', 'm', 'b', 't'] : abbrev
}
NumberAbbreviate.prototype._abbreviate = function(number, decPlaces) {
decPlaces = Math.pow(10, decPlaces)
for (var i = this.abbrev.length - 1; i >= 0; i--) {
var size = Math.pow(10, (i + 1) * 3)
if (size <= number) {
number = Math.round(number * decPlaces / size) / decPlaces
if ((number === 1000) && (i < this.abbrev.length - 1)) {
number = 1
i++
}
number += this.abbrev[i]
break
}
}
return number
}
NumberAbbreviate.prototype.abbreviate = function(number, decPlaces) {
var isNegative = number < 0
var abbreviatedNumber = this._abbreviate(Math.abs(number), decPlaces || 0)
return isNegative ? '-' + abbreviatedNumber : abbreviatedNumber;
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = NumberAbbreviate
} else {
root.NumberAbbreviate = NumberAbbreviate
}
})(this);