Version: Legacy

# Token Quantity Conversion

## Token Amount Conversion#

Since getExpectedRate returns a rate, not the amount, the following code snippets show how to convert to both source and destination token amounts, taking their decimals into account.

### calcSrcQty#

ParameterDescription
dstQtyERC20 destination token amount in its decimals
srcDecimalsERC20 source token decimals
dstDecimalsERC20 destination token decimals
ratesrc -> dst conversion rate, independent of token decimals

Returns:
ERC20 source token amount in its decimals.

#### Javascript#

// DISCLAIMER: Code snippets in this guide are just examples and you
// https://t.me/KyberDeveloper.
function calcSrcQty(dstQty, srcDecimals, dstDecimals, rate) {
const PRECISION = 10 ** 18;
//source quantity is rounded up. to avoid dest quantity being too low.
if (srcDecimals >= dstDecimals) {
numerator = PRECISION * dstQty * 10 ** (srcDecimals - dstDecimals);
denominator = rate;
} else {
numerator = PRECISION * dstQty;
denominator = rate * 10 ** (dstDecimals - srcDecimals);
}
return (numerator + denominator - 1) / denominator; //avoid rounding down errors
}

#### Solidity#

Refer to the Utils contract.

### calcDstQty#

ParameterDescription
srcQtyERC20 source token amount in its decimals
srcDecimalsERC20 source token decimals
dstDecimalsERC20 destination token decimals
ratesrc -> dst conversion rate, independent of token decimals

Returns:
ERC20 destination token amount in its decimals.

#### Javascript#

// DISCLAIMER: Code snippets in this guide are just examples and you
// https://t.me/KyberDeveloper.
function calcDstQty(srcQty, srcDecimals, dstDecimals, rate) {
const PRECISION = 10 ** 18;
if (dstDecimals >= srcDecimals) {
return (srcQty * rate * 10 ** (dstDecimals - srcDecimals)) / PRECISION;
} else {
return (srcQty * rate) / (PRECISION * 10 ** (srcDecimals - dstDecimals));
}
}

#### Solidity#

Refer to the Utils contract.

### calcRateFromQty#

ParameterTypeDescription
srcAmountNumberERC20 source token amount in its decimals
destAmountNumberERC20 source token decimals
srcDecimalsNumberERC20 destination token decimals
dstDecimalsNumbersrc -> dst conversion rate, independent of token decimals

Returns:
Token conversion rate independent of token decimals

#### Javascript#

// DISCLAIMER: Code snippets in this guide are just examples and you
// https://t.me/KyberDeveloper.
function calcRateFromQty(srcAmount, destAmount, srcDecimals, dstDecimals) {
const PRECISION = 10 ** 18;
if (dstDecimals >= srcDecimals) {
return (
(destAmount * PRECISION) / (10 ** (dstDecimals - srcDecimals) * srcAmount)
);
} else {
return (
(destAmount * PRECISION * 10 ** (srcDecimals - dstDecimals)) / srcAmount
);
}
}

#### Solidity#

Refer to the Utils2 contract.