-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatNumber.js
28 lines (23 loc) · 967 Bytes
/
formatNumber.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
const decimalPlaces = require('./decimalPlaces');
const suffixWith = require('./suffixWith');
module.exports = function formatNumber(precision = 1, lessThanOneThousandPrecision = 2) {
return (numberArg) => {
const number = parseFloat(numberArg);
const absNumber = Math.abs(number);
const exponent = Math.max(Math.log(absNumber) / Math.log(10), 0);
const suffixes = ['', 'K', 'M', 'B', 'T'];
const triplet = Math.min(Math.floor(exponent / 3), suffixes.length - 1);
let condensedNumber;
if (triplet > 0) {
condensedNumber = decimalPlaces(precision)(
number / Math.pow(10, triplet * 3)
);
} else {
condensedNumber =
number % 1 === 0
? number.toString()
: decimalPlaces(lessThanOneThousandPrecision)(number);
}
return suffixWith(suffixes[triplet])(condensedNumber);
};
}