Skip to content

Instantly share code, notes, and snippets.

@TomiOhl
Created April 28, 2021 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TomiOhl/1c5ac6126210a89ae632f9e8fd6e3e4c to your computer and use it in GitHub Desktop.
Save TomiOhl/1c5ac6126210a89ae632f9e8fd6e3e4c to your computer and use it in GitHub Desktop.
Converting an amount from one token's decimals to another in Solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
interface IERC20 {
function decimals() external view returns (uint8);
}
contract DecimalsTest {
function changeDecimals(address _fromToken, address _desToken, uint _amount) external view returns (uint) {
return convertDecimals(_amount, getDecimals(_fromToken), getDecimals(_desToken));
}
function getDecimals(address _token) internal view returns (uint8) {
return IERC20(_token).decimals();
}
// Convert from the decimals of token1 to the decimals of token2
// Slight inaccuracy when converting to fewer decimals (approx. a quarter of a usd cent on an ether -> usdc swap)
function convertDecimals(uint _tokenAmount, uint8 _token1decimals, uint8 _token2decimals) internal pure returns (uint) {
if (_token1decimals > _token2decimals)
return _tokenAmount / (10**(_token1decimals - _token2decimals));
else
return _tokenAmount * (10**(_token2decimals - _token1decimals));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment