Token Display with Dynamic Decimal Precision

Token Amount Display Formatting - Single Rule Approach

// INPUT: Token amount as BigInt (smallest unit) + token price
// GOAL: Show enough decimals so that: tokenAmount * price = accurate USD value (±$0.005)

function formatTokenAmount(bigIntAmount, tokenDecimals, tokenPrice) {
    // Step 1: Convert BigInt to decimal number
    tokenAmount = bigIntAmount / 10^tokenDecimals
    
    // Step 2: Calculate USD value
    usdValue = tokenAmount * tokenPrice
    
    // Step 3: Determine decimals needed based on USD value
    if (usdValue < 0.01) {
        // For tiny amounts (< $0.01): Show at least 1 significant digit
        // Find position of first non-zero digit
        decimalsNeeded = countLeadingZeroDecimals(tokenAmount) + 1
    } else {
        // For normal amounts (≥ $0.01): Ensure USD accuracy to 2 decimals
        // We need: tokenAmount * price to be accurate within $0.005 (half cent)
        
        requiredTokenPrecision = $0.005 / tokenPrice
        
        // Example: If BTC price = $60,000
        // requiredTokenPrecision = 0.005 / 60000 = 0.00000008333
        // So we need 8 decimals to ensure USD accuracy
        
        decimalsNeeded = ceil(-log10(requiredTokenPrecision))
    }
    
    // Step 4: Format with calculated decimals
    formatted = tokenAmount.toFixed(min(decimalsNeeded, 8))  // Cap at 8 decimals
    formatted = removeTrailingZeros(formatted)
    formatted = addThousandSeparators(formatted)
    
    return formatted
}

// Examples with this single rule:
// BTC @ $60,000:
//   $30,000 worth = 0.5 BTC      → Shows as "0.5"        (0 decimals needed)
//   $150 worth = 0.0025 BTC      → Shows as "0.0025"     (4 decimals needed)
//   $2 worth = 0.0000333 BTC     → Shows as "0.0000333"  (7 decimals needed)
//   $0.005 worth = 0.00000008 BTC → Shows as "0.00000008" (8 decimals, 1 sig digit)

// ETH @ $3,000:
//   $30,000 worth = 10 ETH       → Shows as "10"         (0 decimals needed)
//   $150 worth = 0.05 ETH        → Shows as "0.05"       (2 decimals needed)
//   $2 worth = 0.000667 ETH      → Shows as "0.000667"   (6 decimals needed)

// Key Benefits of Single Rule:
// • Automatic adaptation to token price
// • Ensures USD value accuracy for all amounts ≥ $0.01
// • Shows meaningful precision for dust amounts < $0.01
// • No arbitrary thresholds - pure math based on price
            
Loading token data...