From 454e8f2b498293e46825432a23a10578c958f173 Mon Sep 17 00:00:00 2001 From: pqhyl07 Date: Thu, 26 Nov 2026 09:58:29 +0800 Subject: [PATCH] Fix decimal scaling in WeiToEthWithDecimals Signed-off-by: pqhyl07 --- shared/math/units.go | 8 ++------ shared/math/units_scale_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) create mode 100644 shared/math/units_scale_test.go diff --git a/shared/math/units.go b/shared/math/units.go index 6250ba2f9..8a62ff0c9 100644 --- a/shared/math/units.go +++ b/shared/math/units.go @@ -1,7 +1,6 @@ package math import ( - "math" "math/big" "strconv" ) @@ -99,10 +98,7 @@ func WeiToEthWithDecimals(amount *big.Int, decimals uint8) float64 { if amount == nil { return 0 } - var weiFloat big.Float - var eth big.Float - weiFloat.SetInt(amount) - eth.Quo(&weiFloat, big.NewFloat(math.Pow(10, float64(decimals)))) - eth64, _ := eth.Float64() + scale := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(decimals)), nil) + eth64, _ := new(big.Rat).SetFrac(amount, scale).Float64() return eth64 } diff --git a/shared/math/units_scale_test.go b/shared/math/units_scale_test.go new file mode 100644 index 000000000..1eb744cf8 --- /dev/null +++ b/shared/math/units_scale_test.go @@ -0,0 +1,25 @@ +package math + +import ( + "math/big" + "testing" +) + +func TestWeiToEthWithDecimalsExactScale(t *testing.T) { + for _, decimals := range []uint8{0, 6, 18, 23, 24, 77, 255} { + scale := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(decimals)), nil) + for _, units := range []int64{1, 3, 7, 12345, -12345, 9007199254740991} { + amount := big.NewInt(units) + want, _ := new(big.Rat).SetFrac(amount, scale).Float64() + if got := WeiToEthWithDecimals(amount, decimals); got != want { + t.Errorf("units=%d decimals=%d: got %.17g, want %.17g", units, decimals, got, want) + } + if amount.Int64() != units { + t.Fatal("input amount was modified") + } + } + } + if WeiToEthWithDecimals(nil, 18) != 0 { + t.Fatal("nil amount must convert to zero") + } +}