Overview
Drift Protocol v2 uses BN.js (BigNum) to represent numerical values with high precision. This is essential because Solana tokens use levels of precision that exceed JavaScript’s standard floating-point number capabilities.All numbers in BN are represented as integers. The precision value indicates how to convert them back to decimal numbers.
How Precision Works
A BigNum value combined with a precision represents a decimal number:Standard Precision Constants
Drift uses consistent precision values across the protocol:Precision Relationships
The BigNum Class
Drift provides aBigNum class that wraps BN with precision-aware operations:
Creating BigNum Values
Arithmetic Operations
Shifting Precision
Display & Formatting
Division Precision Handling
convertToNumber Helper
The SDK provides aconvertToNumber function for safe BN to number conversion:
Implementation
convertToBN Helper
Convert JavaScript numbers to BN with proper precision:Implementation
Common Patterns
Working with Prices
Working with Position Sizes
Calculating Notional Value
Best Practices
- Always use BN for calculations - Never convert to numbers until the final display step
- Match precisions - Ensure values have the same precision before adding/subtracting
- Use helper functions - Prefer
convertToNumber()over manual division - Be careful with multiplication - Precision accumulates, so adjust accordingly
- Handle division carefully - Remember BN division truncates by default