17

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.

9

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

9

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

3

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

0

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, privacy policy and cookie policy

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