import { parseBigInt } from './parseBigInt.ts' export interface NumberToBigIntOptions { /** * The number of digits starting from the right of the returned bigint to consider as decimal * places. * * @default 18n */ precision?: bigint | undefined } /** * Converts a number to a bigint. Decimals to the right of `precision` are truncated. * * @param value - The number to convert to a bigint. * @param options - Conversion options. * @returns The bigint representation of `value` */ export function numberToBigInt(value: number, options?: NumberToBigIntOptions): bigint { const { precision = 18n } = options ?? {} if (precision < 0n) { throw new Error(`[numberToBigInt] \`precision\` must be positive, got ${precision}`) } // If `value` has decimals and `precision` is at least 1, parse it as a string if (value % 1 !== 0 && precision >= 1n) { const parsedValue = parseBigInt(String(value), { precision }) if (parsedValue === null) { throw new Error( `[numberToBigInt] Failed to parse ${value} as a bigint with precision ${precision}`, ) } return parsedValue } else { const precisionFactor = 10n ** precision return BigInt(Math.trunc(value)) * precisionFactor } }