RequireFromString (#73)

fmt
This commit is contained in:
Randy Pensinger 2018-03-01 13:32:36 -08:00 committed by Victor Quinn
parent ca6009d707
commit 69b3a8ad1f
2 changed files with 51 additions and 0 deletions

View file

@ -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:

View file

@ -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