diff --git a/CHANGELOG.md b/CHANGELOG.md index 334dae1f4f19..44a0f174f866 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Features +* [\#10592](https://github.com/cosmos/cosmos-sdk/pull/10592) Add a `DecApproxEq` function that checks to see if `|d1 - d2| < tol` for some Dec `d1, d2, tol`. * [\#10393](https://github.com/cosmos/cosmos-sdk/pull/10393) Add `HasSupply` method to bank keeper to ensure that input denom actually exists on chain. * [\#9933](https://github.com/cosmos/cosmos-sdk/pull/9933) Introduces the notion of a Cosmos "Scalar" type, which would just be simple aliases that give human-understandable meaning to the underlying type, both in Go code and in Proto definitions. * [\#9884](https://github.com/cosmos/cosmos-sdk/pull/9884) Provide a new gRPC query handler, `/cosmos/params/v1beta1/subspaces`, that allows the ability to query for all registered subspaces and their respective keys. diff --git a/types/decimal.go b/types/decimal.go index a6d2868969a1..aebe5abb08e3 100644 --- a/types/decimal.go +++ b/types/decimal.go @@ -801,3 +801,8 @@ func MaxDec(d1, d2 Dec) Dec { func DecEq(t *testing.T, exp, got Dec) (*testing.T, bool, string, string, string) { return t, exp.Equal(got), "expected:\t%v\ngot:\t\t%v", exp.String(), got.String() } + +func DecApproxEq(t *testing.T, d1 Dec, d2 Dec, tol Dec) (*testing.T, bool, string, string, string) { + diff := d1.Sub(d2).Abs() + return t, diff.LTE(tol), "expected |d1 - d2| <:\t%v\ngot |d1 - d2| = \t\t%v", tol.String(), diff.String() +} diff --git a/types/decimal_test.go b/types/decimal_test.go index 8529f5bfe8f5..e2c252581774 100644 --- a/types/decimal_test.go +++ b/types/decimal_test.go @@ -7,6 +7,7 @@ import ( "math/big" "testing" + "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "sigs.k8s.io/yaml" @@ -21,6 +22,29 @@ func TestDecimalTestSuite(t *testing.T) { suite.Run(t, new(decimalTestSuite)) } +func TestDecApproxEq(t *testing.T) { + // d1 = 0.55, d2 = 0.6, tol = 0.1 + d1 := sdk.NewDecWithPrec(55, 2) + d2 := sdk.NewDecWithPrec(6, 1) + tol := sdk.NewDecWithPrec(1, 1) + + require.True(sdk.DecApproxEq(t, d1, d2, tol)) + + // d1 = 0.55, d2 = 0.6, tol = 1E-5 + d1 = sdk.NewDecWithPrec(55, 2) + d2 = sdk.NewDecWithPrec(6, 1) + tol = sdk.NewDecWithPrec(1, 5) + + require.False(sdk.DecApproxEq(t, d1, d2, tol)) + + // d1 = 0.6, d2 = 0.61, tol = 0.01 + d1 = sdk.NewDecWithPrec(6, 1) + d2 = sdk.NewDecWithPrec(61, 2) + tol = sdk.NewDecWithPrec(1, 2) + + require.True(sdk.DecApproxEq(t, d1, d2, tol)) +} + // create a decimal from a decimal string (ex. "1234.5678") func (s *decimalTestSuite) mustNewDecFromStr(str string) (d sdk.Dec) { d, err := sdk.NewDecFromStr(str)