forked from VovanR/format-thousands
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
82 lines (70 loc) · 1.73 KB
/
index.js
File metadata and controls
82 lines (70 loc) · 1.73 KB
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
// (Non-Breaking Space)
var NBSP = String.fromCharCode(160);
function parseNumber(number) {
var isNegative = number < 0;
var numberString = String(number);
if (isNegative) {
numberString = numberString.slice(1);
}
var decimal = numberString.split('.');
return {
integer: decimal[0],
fraction: decimal[1] || '',
sign: isNegative ? '-' : ''
};
}
function format(number, separator) {
number = String(number);
while (number.length % 3) {
number = '#' + number;
}
var result = number.substr(0, 3);
result = result.replace(/#/g, '');
var i;
var length = number.length;
for (i = 3; i < length; i += 3) {
result = result + separator + number.substr(i, 3);
}
return result;
}
/**
* @param {Number} number
* @param {Object|String} [options=' ']
* @param {String} [options.separator=' ']
* @param {Boolean} [options.formatFourDigits=true]
* @returns {String}
*/
module.exports = function (number, options) {
var result = '';
var separator = NBSP;
var formatFourDigits = true;
if (!number && number !== 0) {
return result;
}
var numberObject = parseNumber(number);
var numberString = String(number);
if (typeof options === 'object') {
if (options.separator) {
separator = options.separator;
}
if (typeof options.formatFourDigits === 'boolean') {
formatFourDigits = options.formatFourDigits;
}
} else if (typeof options !== 'undefined') {
separator = options;
}
if (
numberObject.integer.length <= 3 ||
(numberObject.integer.length === 4 && !formatFourDigits)
) {
result = numberString;
} else {
result += numberObject.sign;
result += format(numberObject.integer, separator);
if (numberObject.fraction) {
result += '.';
result += numberObject.fraction;
}
}
return result;
};