我想定义一个这样的函数:
function convert(ufixed x) external pure returns (uint256 result) {
result = x * 1e18;
}不幸的是,上面的代码没有编译:
TypeError: ufixed128x18类型不能隐式转换为预期类型uint256。
我把x扔给了uint256:
result = uint256(x) * 1e18;但这也没用:
UnimplementedFeatureError:不动点类型未实现。
我读过文档,我知道定点类型不能分配给或来自.不过,我只想把它们乘以一个前因子。
难道现在还不可能在坚实的情况下做到这一点吗?
发布于 2022-09-25 16:24:58
目前,我们几乎不能用ufixed类型做任何事情。
您可以实现自己的UFixed类型,也可以使用处理“定点”数字算术的库。
查看以下UFixed自定义类型和FixedMath库,以抽象该类型的算术操作的详细信息:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.16;
type UserId is uint256;
type UFixed is uint256;
/// A minimal library to do fixed point operations on UFixed.
library FixedMath {
uint constant multiplier = 10**18;
/// Adds two UFixed numbers. Reverts on overflow,
/// relying on checked arithmetic on uint256.
function add(UFixed a, UFixed b) internal pure returns (UFixed) {
return UFixed.wrap(UFixed.unwrap(a) + UFixed.unwrap(b));
}
/// Multiplies UFixed and uint256. Reverts on overflow,
/// relying on checked arithmetic on uint256.
function mul(UFixed a, uint256 b) internal pure returns (UFixed) {
return UFixed.wrap(UFixed.unwrap(a) * b);
}
/// Take the floor of a UFixed number.
/// @return the largest integer that does not exceed `a`.
function floor(UFixed a) internal pure returns (uint256) {
return UFixed.unwrap(a) / multiplier;
}
/// Turns a uint256 into a UFixed of the same value.
/// Reverts if the integer is too large.
function toUFixed(uint256 a) internal pure returns (UFixed) {
return UFixed.wrap(a * multiplier);
}
}
contract Contract {
using FixedMath for UFixed;
mapping(UserId => User) public users;
struct User {
UserId id;
string name;
}
function getUser(UserId userId) public view returns(User memory) {
return users[userId];
}
function add(UFixed a, UFixed b) public pure returns(UFixed) {
return a.add(b);
}
}https://ethereum.stackexchange.com/questions/136342
复制相似问题