Understand BN and Precision in the Drift SDK
masterThe Drift SDK uses BigNum (BN) from the bn.js library to handle the high precision required by Solana tokens. All numerical values are represented as integers. To convert these to human-readable numbers, you must account for the precision constant.
Example Calculation:
A BigNum of 10,500,000 with a precision of 10^6 equals 10.5 (10,500,000 / 1,000,000).
Common Precision Constants
| Precision Name | Value |
|---|---|
FUNDING_RATE_BUFFER | 10^3 |
QUOTE_PRECISION | 10^6 |
PEG_PRECISION | 10^6 |
PRICE_PRECISION | 10^6 |
AMM_RESERVE_PRECISION | 10^9 |
BASE_PRECISION | 10^9 |
Handling Division
Because BN only supports integer division (returning the floor), use the convertToNumber helper function to get exact decimal values.
import { convertToNumber } from '@drift-labs/sdk';
import { BN } from 'bn.js'; // or from @drift-labs/sdk
// Using standard BN division (returns floor)
new BN(10500).div(new BN(1000)).toNumber(); // Result: 10
// Manual exact division
new BN(10500).div(new BN(1000)).toNumber() + new BN(10500).mod(new BN(1000)).toNumber(); // Result: 10.5
// Recommended: Use the SDK helper for exact values
convertToNumber(new BN(10500), new BN(1000)); // Result: 10.5import {convertToNumber} from @drift-labs/sdk
// Gets the floor value
new BN(10500).div(new BN(1000)).toNumber(); // = 10
// Gets the exact value
new BN(10500).div(new BN(1000)).toNumber() + BN(10500).mod(new BN(1000)).toNumber(); // = 10.5
// Also gets the exact value
convertToNumber(new BN(10500), new BN(1000)); // = 10.5