diff --git a/helpers.go b/helpers.go index fc3b0bf..036a145 100644 --- a/helpers.go +++ b/helpers.go @@ -110,6 +110,15 @@ func (r rat[T]) String() string { return fmt.Sprintf("%d/%d", r.num, r.den) } +func (r rat[T]) Format(w fmt.State, v rune) { + switch v { + case 'f': + fmt.Fprintf(w, "%f", r.Float64()) + default: + fmt.Fprintf(w, "%s", r.String()) + } +} + func (r *rat[T]) UnmarshalText(text []byte) error { s := string(text) if !strings.Contains(s, "/") { diff --git a/helpers_test.go b/helpers_test.go index 13c9630..6f6d9de 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -5,6 +5,7 @@ package imagemeta import ( "encoding" + "fmt" "testing" qt "github.com/frankban/quicktest" @@ -106,4 +107,12 @@ func TestRat(t *testing.T) { ru, _ = NewRat[uint32](4, 1) c.Assert(ru.String(), qt.Equals, "4") }) + + c.Run("Format", func(c *qt.C) { + ru, _ := NewRat[uint32](1, 3) + s := fmt.Sprintf("%.2f", ru) + c.Assert(s, qt.Equals, "0.333333") + s = fmt.Sprintf("%s", ru) + c.Assert(s, qt.Equals, "1/3") + }) }