Format ERC-20 balances without losing the smallest unit

An ERC-20 balance arrives as an integer. Floating-point conversion can round away a unit before the wallet formats the number.

Split the integer at the decimal boundary

Suppose balanceOf returns 1234567 and this contract reports six decimals. Divide by ten to the sixth power and retain the remainder. Pad the remainder to six digits before formatting.

1234567 div 1000000 = 1
1234567 mod 1000000 = 234567
1.234567

A raw value of 7 displays as 0.000007. Store the raw integer with the chain and contract address so a display setting cannot alter the ledger. Parse user-entered amounts by reversing the operation with integer arithmetic.

Handle a missing decimals method

The base ERC-20 specification makes decimals optional. If the call fails or produces an undecodable response, show the raw amount with its unit clearly labeled or use verified token metadata. Assuming eighteen decimals can hide a balance by many orders of magnitude. eips.ethereum.org ERC-20