Note that floating point numbers are not supported in Solidity and the Ethereum Virtual Machine at the moment.
While your question is asking about converting a string
to an int
, your sample code refers to uint
rather than int
, so I'll provide the solution to convert a string to a uint
.
Following is a solution to convert a non-floating point number from a string to a uint
(which is a uint256
). I've added the solution to this question to my solution to Solidity concatenate uint into a string?:
pragma solidity ^0.4.4;
contract TestIntToString {
string public uintToStringResult;
string public appendUintToStringResult;
uint public stringToUintResult;
function TestIntToString() {
uintToStringResult = uintToString(12345678901234567890);
appendUintToStringResult = appendUintToString("My integer is: ", 1234567890);
stringToUintResult = stringToUint("12312317314571638713891378174163782169246891247193811231231731");
}
function uintToString(uint v) constant returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i + 1);
for (uint j = 0; j <= i; j++) {
s[j] = reversed[i - j];
}
str = string(s);
}
function appendUintToString(string inStr, uint v) constant returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i + 1);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j <= i; j++) {
s[j + inStrb.length] = reversed[i - j];
}
str = string(s);
}
function stringToUint(string s) constant returns (uint result) {
bytes memory b = bytes(s);
uint i;
result = 0;
for (i = 0; i < b.length; i++) {
uint c = uint(b[i]);
if (c >= 48 && c <= 57) {
result = result * 10 + (c - 48);
}
}
}
}
And here's the Browser Solidity screenshot showing the solution works: