Back

blockchain - solidity - flaot 浮点数 divide 除法

发布时间: 2024-04-20 08:36:00

refer to:

solidity中没有浮点数的概念,也没有除法。

2/3 会被识别成:rational_const, 例如:

Compiler run failed:
Error (4486): Type rational_const 312500000000000 / 27 is not implicitly convertible to expected type uint256. Try converting to type ufixed256x64 or use an explicit conversion.
  --> src/ReducingPayout.sol:20:5:
   |
20 |     uint256 reducedPerSecond = (1e18 / 3600 / 24);
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

解决办法:

1. 想办法绕过。 例如,计算1 ether的 0.1%, 那么就是 1e15 wei.

2. 使用math第三方包,例如 

openzepplin的SafeMath (低版本)  , Math(  v5 )   https://docs.openzeppelin.com/contracts/5.x/utilities#math

ABDK math lib:  https://github.com/abdk-consulting/abdk-libraries-solidity/tree/master

Back