Skip to content

Commit c134461

Browse files
committed
Implement Format on rat
See gohugoio/hugo#12718
1 parent 2ced9e0 commit c134461

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

‎helpers.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,15 @@ func (r rat[T]) String() string {
110110
return fmt.Sprintf("%d/%d", r.num, r.den)
111111
}
112112

113+
func (r rat[T]) Format(w fmt.State, v rune) {
114+
switch v {
115+
case 'f':
116+
fmt.Fprintf(w, "%f", r.Float64())
117+
default:
118+
fmt.Fprintf(w, "%s", r.String())
119+
}
120+
}
121+
113122
func (r *rat[T]) UnmarshalText(text []byte) error {
114123
s := string(text)
115124
if !strings.Contains(s, "/") {

‎helpers_test.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package imagemeta
55

66
import (
77
"encoding"
8+
"fmt"
89
"testing"
910

1011
qt "github.com/frankban/quicktest"
@@ -106,4 +107,12 @@ func TestRat(t *testing.T) {
106107
ru, _ = NewRat[uint32](4, 1)
107108
c.Assert(ru.String(), qt.Equals, "4")
108109
})
110+
111+
c.Run("Format", func(c *qt.C) {
112+
ru, _ := NewRat[uint32](1, 3)
113+
s := fmt.Sprintf("%.2f", ru)
114+
c.Assert(s, qt.Equals, "0.333333")
115+
s = fmt.Sprintf("%s", ru)
116+
c.Assert(s, qt.Equals, "1/3")
117+
})
109118
}

0 commit comments

Comments
 (0)