30

How can I achieve proper division of two integers in solidity?

Suppose I perform : 3/2 the solution provided is 1 and not 1.5

please help.

3

5 Answers 5

15

The Fixed Point Numbers documentation has a warning which says:

Fixed point numbers are not fully supported by Solidity yet. They can be declared, but cannot be assigned to or from.

The warning at the bottom of Rational and Integer Literals says:

Division on integer literals used to truncate in earlier versions, but it will now convert into a rational number, i.e. 5 / 2 is not equal to 2, but to 2.5

11

In solidity, float/double data types are not provided till yet. If you want to perform this calculation for ether, you should use the different units of ether.

For more : http://solidity.readthedocs.io/en/develop/units-and-global-variables.html#ether-units

For float query : http://solidity.readthedocs.io/en/latest/frequently-asked-questions.html#how-do-you-represent-double-float-in-solidity

2
8

Make sure you use the safe math library first, and then I usually just multiply the stuff out by 100 or more depending on precision,

So if you just multiply all the numbers in your contract by 100 then 300/2 = 150

2

Solidity does not support floating point values there are many reasons but the most important is that solidity deals with real money and as we all know while division we lose some minor point values when we convert the value back to an integer due to that solidity does not support it.

So what is the other option to perform division like 1/2 == 0.5 and get this result?

So the approach is simple we have to convert the value to WEI (the smallest unit of ether) and then on the frontend side using ethers or any other library we can convert the Wei value back to Ether value.

here is the example

function divide(uint256 a, uint256 b) external pure returns(uint256) {
    require(b != 0, "division by zero will result in infinity.");
    return (a * 1e18) / b;
}

Using this function if we take the above values a=1 and b=2 we will get the result of 500000000000000000 and when we convert this value to Ether value using ethers.js we will get 0.5.

Hope it will help in other situations.

1

You may use divi function from ABDK Math 64.64 library. It divides one integer by another and returns the result as 64.64-bit fixed point number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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