diff --git a/common/format.go b/common/format.go index 6fc21af719..cf2efc0ba4 100644 --- a/common/format.go +++ b/common/format.go @@ -18,9 +18,12 @@ package common import ( "fmt" + "math/big" "regexp" "strings" "time" + + "github.com/ethereum/go-ethereum/params" ) // PrettyDuration is a pretty printed version of a time.Duration value that cuts @@ -80,3 +83,18 @@ func (t PrettyAge) String() string { } 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 +} diff --git a/common/format_test.go b/common/format_test.go new file mode 100644 index 0000000000..41a311321f --- /dev/null +++ b/common/format_test.go @@ -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)) + } +}