Tag Archives: solidity

Converting strings to integers in Solidity

If I have a string representation of a number in the Solidity programming language, how do I convert it to one of the integer types? There are casting operations for converting between the different numeric types:

int8 y = -3;
uint x = uint(y);

But there doesn’t seem to be a built-in string to integer converter. After much Googling and asking the folks at Oraclize for help on on another issue, we found a solution – there is a “parseInt” function built into the Oraclize library. The source code of the relevant function is reproduced here because the nice folks at Oraclize have allowed their code to be used freely:

This code looks through each byte of the string in turn, ensuring it is an ASCII digit and raising it to the appropriate power of ten to convert a string of digits into an integer.

If you are already using Oraclize in your Ethereum contract, then you should have “parseInt” built-in, otherwise you are free to use this code (with the copyright notice) in your own code.