uint 与固体分数的乘法

uint multiplication with fractions in solidity

我正在尝试获得稳定值的下限和上限。

function foo(uint value) public {

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

}

使用上面的代码,我得到以下错误:

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

我的目标是检查传递的值是否在执行某些操作的阈值内。有没有办法在 Solidity 中做到这一点?

正如 documentions 所说 Solidity 还不完全支持小数运算。你有两个选择。

  1. 可以将.51.5转换为multiplicationdivision操作。但是由于输出将是 uint 你将有精度损失。 例如:

    uint value = 5;
    uint lower_threshold = value / 2;//output 2
    uint upper_threshold = value * 3 / 2;//output 7
    
  2. 您可以将 value 与一些 uint value 相乘,以便执行 value / 2 不会有任何精度损失。 例如:

    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
    }