1
votes

I am trying to get a lower and upper threshold on a value in solidity.

function foo(uint value) public {

  uint lower_threshold = value * 0.5;
  uint upper_threshold = value * 1.5;

}

With the above code, I get the following error:

TypeError: Operator * not compatible with types uint32 and rational_const 1 / 2

My goal is to check that the value passed is within the threshold to perform some action. Is there a way to do this in Solidity?

1
You may find useful Mikhail Vladimirov's Math in Solidity series, particularly Part 1: Numbers and Part 2: Overflow. - Paul Razvan Berg

1 Answers

1
votes

As the documentions says Solidity does not fully support decimal operations yet. You have two options there.

  1. You can convert .5 and 1.5 into multiplication and division operations. But as output will be uint you will have precision loss. Ex:

    uint value = 5;
    uint lower_threshold = value / 2;//output 2
    uint upper_threshold = value * 3 / 2;//output 7
    
  2. You can multiply value with some uint value so that performing value / 2 won't have any precision loss. Ex:

    uint value = 5;
    uint tempValue = value * 10;//output 50
    uint lower_threshold = tempValue / 2;//output 25
    uint upper_threshold = tempValue * 3 / 2;//output 75
    
    if(tempValue >= lower_threshold && tempValue <= lower_threshold) {
        //do some stuff
    }