diff --git a/decimal.go b/decimal.go index fba0987..20aa608 100644 --- a/decimal.go +++ b/decimal.go @@ -153,6 +153,22 @@ func NewFromString(value string) (Decimal, error) { }, nil } +// RequireFromString returns a new Decimal from a string representation +// or panics if NewFromString would have returned an error. +// +// Example: +// +// d := RequireFromString("-123.45") +// d2 := RequireFromString(".0001") +// +func RequireFromString(value string) Decimal { + dec, err := NewFromString(value) + if err != nil { + panic(err) + } + return dec +} + // NewFromFloat converts a float64 to Decimal. // // Example: diff --git a/decimal_test.go b/decimal_test.go index 73815ec..25ad751 100644 --- a/decimal_test.go +++ b/decimal_test.go @@ -239,6 +239,41 @@ func TestNewFromStringDeepEquals(t *testing.T) { } } +func TestRequireFromString(t *testing.T) { + s := "1.23" + defer func() { + err := recover() + if err != nil { + t.Errorf("error while parsing %s", s) + } + }() + + d := RequireFromString(s) + if d.String() != s { + t.Errorf("expected %s, got %s (%s, %d)", + s, d.String(), + d.value.String(), d.exp) + } +} + +func TestRequireFromStringErrs(t *testing.T) { + s := "qwert" + var d Decimal + var err interface{} + + func() { + defer func() { + err = recover() + }() + + d = RequireFromString(s) + }() + + if err == nil { + t.Errorf("panic expected when parsing %s", s) + } +} + func TestNewFromFloatWithExponent(t *testing.T) { type Inp struct { float float64