-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
23675b0
commit cf630d2
Showing
2 changed files
with
34 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,38 @@ | ||
import BigNumber from 'bignumber.js' | ||
|
||
/** | ||
* @description Converts a number to a bigint in atomic units | ||
* @description Converts to a bigint in atomic units | ||
* don't use this to format inputs use parseDecimal instead | ||
* bare in mind that only '.' is accepted as decimal separator | ||
* if you pass a localized string it will keep only '.-0-9' characters | ||
* which means that your decimal separator can affect the result in languages that use ',' or ' ' as decimal separator | ||
* | ||
* @param quantity string | number | BigNumber | ||
* @param decimalPlaces | ||
* @param {string | number | BigNumber} quantity | ||
* @param {number[0]} decimalPlaces | ||
* @param {boolean} absolute | ||
* @returns bigint with atomic units | ||
* | ||
* @example | ||
* toBigInt('123456789', 0) // => 123456789n | ||
* toBigInt('123456789.000000000000000001', 18) // => 123456789000000000000000001n | ||
* toBigInt('1', 18) // => 1000000000000000000n | ||
* toBigInt('-1', 18) // => -1000000000000000000n | ||
*/ | ||
export function toBigInt( | ||
quantity: string | number | BigNumber, | ||
decimalPlaces: number, | ||
decimalPlaces = 0, | ||
absolute = false, | ||
): bigint { | ||
const bigNumber = BigNumber(quantity || 0) | ||
const sanitized = | ||
typeof quantity === 'string' | ||
? quantity.replace(/(?!^-)[^\d.-]/g, '') | ||
: quantity | ||
const bigNumber = BigNumber(sanitized || 0) | ||
|
||
const scaledNumber = bigNumber.shiftedBy(decimalPlaces) | ||
|
||
return BigInt(scaledNumber.toFixed(0, BigNumber.ROUND_DOWN)) | ||
const bi = BigInt(scaledNumber.toFixed(0, BigNumber.ROUND_DOWN)) | ||
|
||
if (!absolute) return bi | ||
|
||
return bi < 0n ? -bi : bi | ||
} |