package dec import "testing" func TestParseString(t *testing.T) { cases := map[string]string{ "8.105000000000000000": "8.105", "0": "0", "-0.5": "-0.5", ".25": "0.25", "75924.000000000000000000": "75924", "0.000000000000000001": "0.000000000000000001", "+3": "3", } for in, want := range cases { d, err := Parse(in) if err != nil { t.Fatalf("Parse(%q): %v", in, err) } if got := d.String(); got != want { t.Errorf("Parse(%q).String() = %q, want %q", in, got, want) } } for _, bad := range []string{"", "-", "1e5", "1.2.3", "abc", "0.0000000000000000001", "."} { if _, err := Parse(bad); err == nil { t.Errorf("Parse(%q) accepted, want error", bad) } } } func TestArithmetic(t *testing.T) { a, b := MustParse("8.105"), MustParse("53.846") if got := a.Mul(b).String(); got != "436.42183" { t.Errorf("Mul = %s", got) } if got := MustParse("1").Quo(MustParse("3")).String(); got != "0.333333333333333333" { t.Errorf("Quo 1/3 = %s", got) } if got := MustParse("2").Quo(MustParse("3")).String(); got != "0.666666666666666667" { t.Errorf("Quo 2/3 = %s (want half-up)", got) } if got := MustParse("-2").Quo(MustParse("3")).String(); got != "-0.666666666666666667" { t.Errorf("Quo -2/3 = %s", got) } } func TestTicks(t *testing.T) { tick := MustParse("0.001") if !MustParse("8.105").IsMultipleOf(tick) || MustParse("8.1055").IsMultipleOf(tick) { t.Fatal("IsMultipleOf wrong") } if got := MustParse("8.1059").FloorTo(tick).String(); got != "8.105" { t.Errorf("FloorTo = %s", got) } if got := MustParse("8.1051").CeilTo(tick).String(); got != "8.106" { t.Errorf("CeilTo = %s", got) } if got := MustParse("-1.5").FloorTo(MustParse("1")).String(); got != "-2" { t.Errorf("FloorTo negative = %s", got) } } func FuzzParseRoundTrip(f *testing.F) { for _, s := range []string{"0", "1.5", "-0.000000000000000001", "123456789.987654321"} { f.Add(s) } f.Fuzz(func(t *testing.T, s string) { d, err := Parse(s) if err != nil { return } d2, err := Parse(d.String()) if err != nil || !d2.Equal(d) { t.Fatalf("round trip %q -> %q failed", s, d.String()) } }) }