From 1aec7720a8d2d998c64fa9969958f79e8aff6ebd Mon Sep 17 00:00:00 2001 From: Evan Shaw Date: Mon, 12 Dec 2016 15:00:26 +1300 Subject: [PATCH] Add Sign method d.Sign() is a more convenient way of saying d.Cmp(Zero). --- decimal.go | 13 +++++++++++++ decimal_test.go | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/decimal.go b/decimal.go index 3942b3d..5c12280 100644 --- a/decimal.go +++ b/decimal.go @@ -411,6 +411,19 @@ func (d Decimal) Equals(d2 Decimal) bool { return d.Equal(d2) } +// Sign returns: +// +// -1 if d < 0 +// 0 if d == 0 +// +1 if d > 0 +// +func (d Decimal) Sign() int { + if d.value == nil { + return 0 + } + return d.value.Sign() +} + // Exponent returns the exponent, or scale component of the decimal. func (d Decimal) Exponent() int32 { return d.exp diff --git a/decimal_test.go b/decimal_test.go index 718943a..1ff7df1 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -506,6 +506,9 @@ func TestDecimal_Uninitialized(t *testing.T) { if a.Cmp(b) != 0 { t.Errorf("a != b") } + if a.Sign() != 0 { + t.Errorf("a.Sign() != 0") + } if a.Exponent() != 0 { t.Errorf("a.Exponent() != 0") } @@ -1292,6 +1295,22 @@ func TestPow(t *testing.T) { } } +func TestDecimal_Sign(t *testing.T) { + if Zero.Sign() != 0 { + t.Errorf("%q should have sign 0", Zero) + } + + one := New(1, 0) + if one.Sign() != 1 { + t.Errorf("%q should have sign 1", one) + } + + mone := New(-1, 0) + if mone.Sign() != -1 { + t.Errorf("%q should have sign -1", mone) + } +} + func didPanic(f func()) bool { ret := false func() {