Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tpl/inflect: Add the SI function to format numbers with SI notation #12563

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
Loading