Solidity – How to Concatenate Uint into a String?

contract-designcontract-developmentsoliditystring

How would I concatenate an integer into a string using solidity?

For instance, say I have the following:

uint myInteger = 12

How can I create the following string "My integer is: 12" with 12 being the value of myInteger.

In other words have, "My integer is: " + myInteger

Best Answer

Try the following:

pragma solidity ^0.4.4;

contract TestIntToString {

    string public result;

    function TestIntToString() {
        // result = uintToString(12345678901234567890);
        result = appendUintToString("My integer is: ", 1234567890);
    }

    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);
        for (uint j = 0; j < i; j++) {
            s[j] = reversed[i - 1 - 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);
        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 - 1 - j];
        }
        str = string(s);
    }
}

Here is the Browser Solidity screen showing the workings of this algorithm:

enter image description here