0

I'm writing a contract that evaluates (foo/x)*x to give equivalent of math.floor(foo/x)*x. It works, but if I hard code numbers instead (I don't need to do that, just interested), (5/6)*5, it is not allowed in Remix. What is the rationale for that? I'm mostly asking to know if using (foo/x)*x is a bit of a hack, or if the language supports that intentionally (if it does, just don't see why (5/6)*5 is not allowed.. )

0

1 Answer 1

1

The expression 5 / 6 is interpreted by the compiler as a rational constant (fixed or ufixed).

Therefore, such constant value cannot be assigned to an integer variable (uint or int).

On the other hand, when you do:

uint x = 5;
x /= 6;

The compiler replaces the / operation with the opcode for integer division, which is perfectly valid.

You can read more about fixed-point numbers in the official documentation.

4
  • Thanks that makes sense. I did not know functionality to interpret as non-integers/fraction was there. But since it is, perfectly understandable.
    – Johan
    Commented Sep 22, 2020 at 13:31
  • It looks like it is allowed prior to 0.3.3, and the changelog here says fractional/rational constants were added then, github.com/ethereum/solidity/blob/develop/Changelog.md. I started writing Solidity contracts before 0.3.3, and I assumed fractions were still not allowed, which is why I could not understand :)
    – Johan
    Commented Sep 22, 2020 at 13:40
  • @Johan: Wow, before 0.4? You must be one of the earliest adapters in the eco-system! Commented Sep 22, 2020 at 13:47
  • I was early. But still not good at the computer science aspects :) I self-describe as specialized in social coordination system design.
    – Johan
    Commented Sep 22, 2020 at 15:26

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.