In pseudo-code:

uint basePrice = shop.basePrices(_Index_);
float rate = increaseRate(_index) / 100,
float multiplier = math:pow((1 + rate), _amount),
floor(basePrice * Multiplier).

I want to end up with an integer. How can I do multiplication on decimals then floor it at the end to give a nice uint result?


This compiled.

function cost(uint _minerIndex, uint _owned) public pure returns (uint) {
    uint basePrice = shop.basePrices(_minerIndex_);
    uint rate = baseRates(_minerIndex) * 100;
    return (basePrice * ((1 + rate) ** _owned)) / 100;

but I don't see how I could extract this logic to use floating points at all, The documentation talks about rational numbers but gives zero examples of instantiating a rational number.


Solidity doesn't support float point. However, you can represent numbers with a decimal point. You can define a variable that contains the number of decimals you want to have.

For example, If you want to multiply 2.1 by 2.5 you can pass the numbers as 21 and 25 and the value for your decimal points is 1. This is necessary because solidity will not take decimal numbers. You can then multiply 21x25 and divide by 100 (10**decimal)(10**decimal) or 10**(decimal**2) (the two is because you are multiplying "2" numbers) this will give you 525/100 = 5 (in solidity) you can get the remainder (25) as well using (%)

The following function will do the job:

function multiply(uint a, uint b, uint decimals) public returns(uint){
    uint result = (a*b)/(10**(decimals**2));
    return result;

note that a and b are the numbers you want to multiply. If your numbers are (for instance) 1.256 and 2.4588 you must pass 12560 and 24588 and decimals should be equal to 4 (the biggest number of decimals observed in a or b).

I hope this helps.

| improve this answer | |
  • Thanks, how can I work this into the code using exponents? I have to undo the exponentiation of the decimal number – quantumpotato Mar 6 '18 at 3:14
  • Sure. I edited the answer to include a function that does the multiplication indicating the decimals. As your numbers are in decimals I am assuming you are passing them to the function (manually). If this answer your question please accept the answer. – Jaime Mar 6 '18 at 8:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.