-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnumber-formatter.js
60 lines (57 loc) · 1.54 KB
/
number-formatter.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
var NumberFormatter = (function(){
function create(){
var numberFormatter = {};
bind(numberFormatter);
numberFormatter.init();
return numberFormatter;
}
function bind(numberFormatter){
numberFormatter.init = init.bind(numberFormatter);
numberFormatter.prefix = prefix.bind(numberFormatter);
numberFormatter.suffix = suffix.bind(numberFormatter);
numberFormatter.round = round.bind(numberFormatter);
numberFormatter.showSign = showSign.bind(numberFormatter);
numberFormatter.decimals = decimals.bind(numberFormatter);
numberFormatter.format = format.bind(numberFormatter);
}
function init(){
this.options = {
prefix : "",
suffix : "",
round : function(){},
showSign : false,
decimals : null
};
}
function prefix(text){
this.options.prefix = text;
return this;
}
function suffix(text){
this.options.suffix = text;
return this;
}
function round(roundFunc){
this.options.round = roundFunc;
return this;
}
function decimals(decimalPlaces){
this.options.decimals = decimalPlaces;
return this;
}
function showSign(shouldShowSign){
this.showSign = shouldShowSign === false ? false : true;
return this;
}
function format(value){
value = this.options.round(value);
if(this.options.decimals){
value = value.toFixed(this.options.decimals);
}
var textValue = prefix + value + suffix;
if(this.options.showSign && value > 0){
textValue = "+" + textValue;
}
return textValue;
}
});