/**
* Converts a decimal amount of nano from one unit divider to another.
*
-* @param {(bigint|string)} amount - Decimal amount to convert
+* @param {(bigint|number|string)} amount - Decimal amount to convert
* @param {string} inputUnit - Current denomination
* @param {string} outputUnit - Desired denomination
*/
-export async function convert (amount: bigint | string, inputUnit: string, outputUnit: string): Promise<string>
-export async function convert (amount: unknown, inputUnit: unknown, outputUnit: unknown): Promise<string> {
- if (typeof amount !== 'bigint' && typeof amount !== 'string') {
+export function convert (amount: bigint | number | string, inputUnit: string, outputUnit: string): string
+export function convert (amount: bigint | number | string, inputUnit: string, outputUnit: string, format?: 'bigint' | 'string'): bigint
+export function convert (amount: unknown, inputUnit: unknown, outputUnit: unknown, format?: unknown): bigint | string {
+ if (typeof amount !== 'bigint' && typeof amount !== 'number' && typeof amount !== 'string') {
throw new Error('Invalid amount', { cause: typeof amount })
}
if (typeof amount === 'string' && !/^[0-9]+\.?[0-9]*$/.test(amount)) {
throw new Error(`Unknown denomination ${outputUnit}, expected one of the following: ${Object.keys(UNITS)}`)
}
- let i = '0', f = '0'
- if (typeof amount === 'bigint') {
- i = amount.toString()
- } else {
- [i, f] = amount.split('.')
- }
+ let [i, f] = typeof amount === 'string'
+ ? amount.split('.')
+ : amount.toString().split('.')
// convert to raw
const inUnit = UNITS[inputUnit.toUpperCase()]
if (int < 1n) {
throw new Error('Amount must be at least 1 raw')
}
- i = int.toString().padStart(40, '0')
+ if (format === 'bigint') {
+ return int
+ }
// convert to desired denomination
const outUnit = UNITS[outputUnit.toUpperCase()]
+ i = int.toString().padStart(40, '0')
f = i.slice(40 - outUnit).replace(/0*$/g, '')
i = i.slice(0, 40 - outUnit).replace(/^0*/g, '')