added utility methods ToGwei and ToEth with tests

This commit is contained in:
lmittmann 2019-01-06 17:56:45 +01:00
parent fe03b76ffe
commit fe0d2bab52
2 changed files with 84 additions and 0 deletions

View file

@ -18,9 +18,12 @@ package common
import ( import (
"fmt" "fmt"
"math/big"
"regexp" "regexp"
"strings" "strings"
"time" "time"
"github.com/ethereum/go-ethereum/params"
) )
// PrettyDuration is a pretty printed version of a time.Duration value that cuts // PrettyDuration is a pretty printed version of a time.Duration value that cuts
@ -80,3 +83,18 @@ func (t PrettyAge) String() string {
} }
return result return result
} }
// ToGWei converts the big.Int wei to its gwei string representation.
func ToGWei(wei *big.Int) string {
return ToEth(new(big.Int).Mul(wei, big.NewInt(params.GWei)))
}
// ToEth converts the big.Int wei to its ether string representation.
func ToEth(wei *big.Int) string {
z, m := new(big.Int).DivMod(wei, big.NewInt(params.Ether), new(big.Int))
if m.Cmp(new(big.Int)) == 0 {
return z.String()
}
s := strings.TrimRight(fmt.Sprintf("%018s", m.String()), "0")
return z.String() + "." + s
}

66
common/format_test.go Normal file
View file

@ -0,0 +1,66 @@
package common
import (
"math/big"
"testing"
)
func TestToGwei(t *testing.T) {
var tests = []struct {
wei *big.Int
gwei string
}{
{big.NewInt(0), "0"},
{big.NewInt(1), "0.000000001"},
{big.NewInt(1000), "0.000001"},
{big.NewInt(1000000), "0.001"},
{big.NewInt(1000000000), "1"},
{big.NewInt(1100000000), "1.1"},
{big.NewInt(1000100000), "1.0001"},
}
for _, test := range tests {
t.Logf("%v", test.wei)
actual := ToGWei(test.wei)
if actual != test.gwei {
t.Errorf("%v != %v", actual, test.gwei)
}
}
}
func TestToEth(t *testing.T) {
var tests = []struct {
wei *big.Int
eth string
}{
{big.NewInt(0), "0"},
{big.NewInt(1), "0.000000000000000001"},
{big.NewInt(1000), "0.000000000000001"},
{big.NewInt(1000000), "0.000000000001"},
{big.NewInt(1000000000), "0.000000001"},
{big.NewInt(1000000000000), "0.000001"},
{big.NewInt(1000000000000000), "0.001"},
{big.NewInt(1000000000000000000), "1"},
{big.NewInt(1100000000000000000), "1.1"},
{big.NewInt(1000100000000000000), "1.0001"},
}
for _, test := range tests {
actual := ToEth(test.wei)
if actual != test.eth {
t.Errorf("%v != %v", actual, test.eth)
}
}
}
func BenchmarkToEth(b *testing.B) {
for n := 0; n < b.N; n++ {
ToEth(big.NewInt(1))
}
}
func BenchmarkToEth2(b *testing.B) {
for n := 0; n < b.N; n++ {
ToEth(big.NewInt(1000000000000000000))
}
}