首页 > 解决方案 > uint乘法与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 中做到这一点?

标签: solidity

解决方案


正如文档所说,Solidity还不完全支持十进制运算。你有两个选择。

  1. 您可以将.5and转换1.5multiplicationanddivision操作。但是由于输出将是 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
    }
    

推荐阅读