首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不动点类型的实相乘

不动点类型的实相乘
EN

Ethereum用户
提问于 2022-09-25 15:52:52
回答 1查看 268关注 0票数 2

我想定义一个这样的函数:

代码语言:javascript
复制
function convert(ufixed x) external pure returns (uint256 result) {
    result = x * 1e18;
}

不幸的是,上面的代码没有编译:

TypeError: ufixed128x18类型不能隐式转换为预期类型uint256。

我把x扔给了uint256

代码语言:javascript
复制
result = uint256(x) * 1e18;

但这也没用:

UnimplementedFeatureError:不动点类型未实现。

我读过文档,我知道定点类型不能分配给或来自.不过,我只想把它们乘以一个前因子。

难道现在还不可能在坚实的情况下做到这一点吗?

EN

回答 1

Ethereum用户

发布于 2022-09-25 16:24:58

目前,我们几乎不能用ufixed类型做任何事情。

您可以实现自己的UFixed类型,也可以使用处理“定点”数字算术的库。

查看以下UFixed自定义类型和FixedMath库,以抽象该类型的算术操作的详细信息:

代码语言:javascript
复制
// 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);
    }

}
票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/136342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档