|
1
|
import BigNumber from "bignumber.js" |
|
2
|
|
|
3
|
/** |
|
4
|
* Gets the number of decimal places in a number |
|
5
|
* @param num - The number for which we are getting the number of decimal places |
|
6
|
* @returns The number of decimal places |
|
7
|
* |
|
8
|
* @example |
|
9
|
* getDecimalPlaces(123.456) // 3 |
|
10
|
* getDecimalPlaces(42) // 0 |
|
11
|
* getDecimalPlaces(10.0000) // 0 |
|
12
|
*/ |
|
13
|
export function getNumberOfDecimalPlaces(num: number): number { |
|
14
|
// Convert to string and check if it contains a decimal point |
|
15
|
const str = num.toString() |
|
16
|
if (str.indexOf(".") === -1) { |
|
17
|
return 0 |
|
18
|
} |
|
19
|
// Return the length of the part after the decimal point |
|
20
|
return str.split(".")[1].length |
|
21
|
} |
|
22
|
|
|
23
|
/** |
|
24
|
* A private clone so the arithmetic below is immune to any global |
|
25
|
* `BigNumber.config` call elsewhere in the bundle. Twenty decimal places (the |
|
26
|
* library default) only bounds non-terminating division such as `10 / 3`, and |
|
27
|
* comfortably exceeds the ~17 significant digits a JS number can carry, so |
|
28
|
* converting the result back with `toNumber` loses nothing. |
|
29
|
*/ |
|
30
|
const Decimal = BigNumber.clone({ DECIMAL_PLACES: 20 }) |
|
31
|
|
|
32
|
/** |
|
33
|
* Multiplies two numbers without the representation error binary floating |
|
34
|
* point introduces for decimal operands |
|
35
|
* |
|
36
|
* @example |
|
37
|
* 3 * 0.1 // 0.30000000000000004 |
|
38
|
* multiplyDecimal(3, 0.1) // 0.3 |
|
39
|
*/ |
|
40
|
export function multiplyDecimal(a: number, b: number): number { |
|
41
|
return new Decimal(a).times(b).toNumber() |
|
42
|
} |
|
43
|
|
|
44
|
/** |
|
45
|
* Divides two numbers without the representation error binary floating point |
|
46
|
* introduces for decimal operands. Matters most when the caller rounds the |
|
47
|
* result, since an error in the last bit changes the rounded value. |
|
48
|
* |
|
49
|
* @example |
|
50
|
* Math.floor(7 / 0.07) // 99 |
|
51
|
* Math.floor(divideDecimal(7, 0.07)) // 100 |
|
52
|
*/ |
|
53
|
export function divideDecimal(a: number, b: number): number { |
|
54
|
return new Decimal(a).div(b).toNumber() |
|
55
|
} |