diff options
author | Randy Pensinger <rspensinger@gmail.com> | 2018-03-02 05:32:36 +0800 |
---|---|---|
committer | Victor Quinn <mail@victorquinn.com> | 2018-03-02 05:32:36 +0800 |
commit | 69b3a8ad1f5f2c8bd855cb6506d18593064a346b (patch) | |
tree | 0ea2d0a515f9cd247434b2407bdbc7f940afc72f | |
parent | ca6009d7078722b2b6f504b5bf86564d3f6d2913 (diff) | |
download | dexon-decimal-69b3a8ad1f5f2c8bd855cb6506d18593064a346b.tar.gz dexon-decimal-69b3a8ad1f5f2c8bd855cb6506d18593064a346b.tar.zst dexon-decimal-69b3a8ad1f5f2c8bd855cb6506d18593064a346b.zip |
RequireFromString (#73)1.0.1
fmt
-rw-r--r-- | decimal.go | 16 | ||||
-rw-r--r-- | decimal_test.go | 35 |
2 files changed, 51 insertions, 0 deletions
@@ -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 |