exchange.IO("toUnits", ...)
Converts a human-readable amount into an on-chain integer. The entire conversion is performed as an exact calculation on strings, without any floating-point arithmetic.
exchange.IO(k, amount, decimals)Examples
Convert amounts of USDC and ETH.
javascript
function main() {
var USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
// Human-readable amount -> on-chain integer; the precision can be a number or a token address
// (decimals is read automatically)
Log(exchange.IO("toUnits", "1.5", 6))
// Output: 1500000
Log(exchange.IO("toUnits", "1.5", USDC))
// Output: 1500000
Log(exchange.IO("toUnits", "0.01", 18))
// Output: 10000000000000000
// On-chain integer -> human-readable amount
Log(exchange.IO("fromUnits", "1500000", 6))
// Output: 1.5
var raw = exchange.IO("api", USDC, "balanceOf", exchange.IO("address"))
Log("USDC balance:", exchange.IO("fromUnits", raw, USDC))
// Reports an error when there are more decimal places than the precision, instead of silently
// truncating
Log(exchange.IO("toUnits", "1.0000001", 6), GetLastError())
}Returns
| Type | Description |
string | Returns the on-chain integer (as a decimal string). When the number of decimal places exceeds the precision, it returns a null value and reports an error instead of silently truncating. |
Arguments
| Name | Type | Required | Description |
k | string | Yes | Function of the |
amount | string / number | Yes | Human-readable amount, for example |
decimals | number / string | Yes | Precision. You can pass a number (for example, 6 for USDC and 18 for ETH), or a token contract address, in which case the |
See Also
Remarks
It is the inverse operation of exchange.IO("fromUnits", ...).