首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将NEthereum的BigInteger平衡从WEI转换为ETH?

如何将NEthereum的BigInteger平衡从WEI转换为ETH?
EN

Ethereum用户
提问于 2016-05-23 05:10:35
回答 1查看 7.3K关注 0票数 8

我使用这个简单的代码来获得NEthereum的余额:

代码语言:javascript
复制
using System;
using System.Numerics;

namespace TestConsole
{
    class Program
    {
        static readonly BigInteger ethToWeiRatio = new BigInteger(1000000000000000000m);

        static void Main(string[] args)
        {
            var web3 = new Nethereum.Web3.Web3();
            var accountsTask = web3.Eth.Accounts.SendRequestAsync();
            accountsTask.Wait();
            var accounts = accountsTask.Result;
            foreach (var account in accounts)
            {
                Console.WriteLine("account " + account);
            }
            foreach (var account in accounts)
            {
                var balanceTask = web3.Eth.GetBalance.SendRequestAsync(account);
                balanceTask.Wait();
                var balance = balanceTask.Result;
                Console.WriteLine("account " + account + "; balance in wei: "
                                  + balance.Value);
            }
            foreach (var account in accounts)
            {
                var balanceTask = web3.Eth.GetBalance.SendRequestAsync(account);
                balanceTask.Wait();
                var balance = balanceTask.Result;
                Console.WriteLine("account " + account + "; balance in eth: "
                      + BigInteger.Divide(balance.Value, ethToWeiRatio));
            }
        }
    }
}

第一个foreach循环工作,但第三个没有工作。我猜在第二个前额打印的余额是以魏单位,所以我必须把他们转换为Eth。但是,在这两种情况下,结果都是0,这是错误的,因为帐户之间的余额是不同的。

这是完整的输出:

代码语言:javascript
复制
account 0xd74c7d19e3bff6b150f76cac754a65df3b23b755
account 0xa9f4a7d4d7a163bc9f45e2e1e216b7f40ce79af5
account 0xd74c7d19e3bff6b150f76cac754a65df3b23b755; balance in wei: 542316352000000000
account 0xa9f4a7d4d7a163bc9f45e2e1e216b7f40ce79af5; balance in wei: 300000000000000000
account 0xd74c7d19e3bff6b150f76cac754a65df3b23b755; balance in eth: 0
account 0xa9f4a7d4d7a163bc9f45e2e1e216b7f40ce79af5; balance in eth: 0

更新1:刚刚找到了一个丑陋的解决方案:decimal.Parse(balance.Value.ToString())/10000000000000000m

更新2:库的作者推荐了一个新的API:https://github.com/Nethereum/Nethereum/blob/master/src/Nethereum.Util/UnitConversion.cs (还没有测试它)。

EN

回答 1

Ethereum用户

发布于 2016-05-23 14:17:20

Web3中有一个帮助转换器函数,类似于在web3.js中实现的函数。

它可用于以下方面:

web3.Convert.ToWei()或web3.Convert.FromWei()

或作为静态方法Nethereum.Web3.Web3.Convert.ToWei()或Nethereum.Web3.Web3.Convert.FromWei()

请看一下不同重载的代码。

https://github.com/Nethereum/Nethereum/blob/master/src/Nethereum.Util/UnitConversion.cs

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

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

复制
相关文章

相似问题

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