Skip to content

Commit

Permalink
tpl/inflect: Add the SI function to format numbers with SI notation
Browse files Browse the repository at this point in the history
  • Loading branch information
razonyang committed Jun 2, 2024
1 parent 0221ddb commit 55c0ce7
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
19 changes: 19 additions & 0 deletions tpl/inflect/inflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"strconv"
"strings"

_humanize "github.com/dustin/go-humanize"
_inflect "github.com/gobuffalo/flect"
"github.com/spf13/cast"
)
Expand Down Expand Up @@ -73,3 +74,21 @@ func (ns *Namespace) Singularize(v any) (string, error) {

return _inflect.Singularize(word), nil
}

// SI formats numbers with SI notation.
func (ns *Namespace) SI(v any, args ...any) (string, error) {
number, err := cast.ToFloat64E(v)
if err != nil {
return "", err
}

unit := ""
if len(args) > 0 {
unit, err = cast.ToStringE(args[0])
if err != nil {
return "", err
}
}

return strings.TrimSuffix(_humanize.SI(number, unit), " "), nil
}
35 changes: 35 additions & 0 deletions tpl/inflect/inflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,38 @@ func TestInflect(t *testing.T) {
c.Assert(result, qt.Equals, test.expect)
}
}

func TestSI(t *testing.T) {
t.Parallel()
c := qt.New(t)

ns := New()

for _, test := range []struct {
in any
args []any
expect any
}{
{12, []any{}, "12"},
{"123", []any{}, "123"},
{1234, []any{}, "1.234 k"},
{"2345", []any{}, "2.345 k"},
{1234000, []any{}, "1.234 M"},
{"2345000", []any{}, "2.345 M"},
{"0.00000000223", []any{"M"}, "2.23 nM"},
{"1000000", []any{"B"}, "1 MB"},
{"2.2345e-12", []any{"F"}, "2.2345 pF"},
{"invalid-number", []any{}, false},
} {

result, err := ns.SI(test.in, test.args...)

if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil))
continue
}

c.Assert(err, qt.IsNil)
c.Assert(result, qt.Equals, test.expect)
}
}

0 comments on commit 55c0ce7

Please sign in to comment.