Keep a swap amount as text until you convert it directly to an integer. Multiplying a JavaScript Number by a power of ten can lose precision before BigInt ever receives the result.
A conversion contract
Define accepted input syntax first. A form may permit an optional decimal point and decimal digits while rejecting negatives, exponent notation and thousands separators. Localized display is a separate concern: normalize a recognized locale before parsing rather than guessing whether a comma is a decimal separator.
For a hypothetical token with six decimals, split 3.125 into whole 3 and fractional 125, pad the fraction to six places and combine them into 3125000 base units. If the fractional part contains more than six significant decimal places, show a validation error. The ERC-20 decimals convention defines this display relationship; it does not require every token to use eighteen decimals.
Example cases for a six-decimal asset
"3.125" → "3125000"
"0.000001" → "1"
"0.0000001" → reject excess precision
"1e6" → reject unsupported syntaxPreserve exact values after parsing
Use integer arithmetic for balances, allowance comparisons and minimum amounts. Format an integer back into a decimal string for display. BigInt has separate arithmetic and serialization rules; convert amounts to decimal strings at a JSON boundary instead of assuming JSON.stringify accepts native BigInt values.
Also validate the provider's expected range. A positive integer that exceeds a field's width is still invalid. Your fixtures should include a very large amount, the smallest supported unit, leading zeros and an empty field. Compare round trips by exact integer equality, not by a rounded screen label.
Sources & verification (2)
Source-check date is recorded in the article details. URLs are provided for manual verification. Use Copy to keep this page open.
- ERC-20: Token Standard
Token units, optional metadata and allowance semantics
https://eips.ethereum.org/EIPS/eip-20 - BigInt
Integer precision and JSON serialization
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt