aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/big_number_input.ts
blob: 370d91a0ab1d987321c970808333accb46f225d2 (plain) (blame)
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
import { BigNumber } from '@0x/utils';
import * as _ from 'lodash';

/**
 *  A BigNumber extension that is more flexible about decimal strings.
 *  Such as allowing:
 *  new BigNumberInput('0.') => 0
 *  new BigNumberInput('1.') => 1
 *  new BigNumberInput('1..') => still throws
 */
export class BigNumberInput extends BigNumber {
    private readonly _isEndingWithDecimal: boolean;
    constructor(numberOrString: string | number) {
        if (_.isString(numberOrString)) {
            const hasDecimalPeriod = _.endsWith(numberOrString, '.');
            let internalString = numberOrString;
            if (hasDecimalPeriod) {
                internalString = numberOrString.slice(0, -1);
            }
            super(internalString);
            this._isEndingWithDecimal = hasDecimalPeriod;
        } else {
            super(numberOrString);
            this._isEndingWithDecimal = false;
        }
    }
    public toDisplayString(): string {
        const internalString = super.toString();
        if (this._isEndingWithDecimal) {
            return `${internalString}.`;
        }
        return internalString;
    }
}