Skip to content

Commit

Permalink
feat(num): support custom formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
ernado committed Nov 8, 2021
1 parent ba4dd57 commit c56b7b7
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ linters-settings:
- commentedOutCode
- appendAssign
- unnecessaryBlock
- redundantSprint

linters:
disable-all: true
Expand Down
26 changes: 26 additions & 0 deletions num.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package jx

import (
"bytes"
"fmt"
"math/big"

"github.com/go-faster/errors"
)
Expand Down Expand Up @@ -114,6 +116,30 @@ func (n Num) String() string {
return string(n)
}

// Format implements fmt.Formatter.
func (n Num) Format(f fmt.State, verb rune) {
switch verb {
case 's', 'v':
_, _ = f.Write(n)
case 'd':
d, err := n.Int64()
if err != nil {
fmt.Fprintf(f, "%%!invalid(Num=%s)", n.String())
return
}
v := big.NewInt(d)
v.Format(f, verb)
case 'f':
d, err := n.Float64()
if err != nil {
fmt.Fprintf(f, "%%!invalid(Num=%s)", n.String())
return
}
v := big.NewFloat(d)
v.Format(f, verb)
}
}

// Sign reports sign of number.
//
// 0 is zero, 1 is positive, -1 is negative.
Expand Down
10 changes: 10 additions & 0 deletions num_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package jx

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -21,6 +22,15 @@ func TestEncoder_Num(t *testing.T) {
}

func TestNum(t *testing.T) {
t.Run("Format", func(t *testing.T) {
assert.Equal(t, `-12`, fmt.Sprintf("%d", Num(`"-12.0"`)))
assert.Equal(t, `-12.000000`, fmt.Sprintf("%f", Num(`"-12.0"`)))
assert.Equal(t, `%!invalid(Num=f)`, fmt.Sprintf("%f", Num(`f`)))
assert.Equal(t, `"-12.0"`, fmt.Sprintf("%s", Num(`"-12.0"`)))
assert.Equal(t, `"-12.0"`, fmt.Sprintf("%v", Num(`"-12.0"`)))
assert.Equal(t, `%!invalid(Num=f)`, fmt.Sprintf("%d", Num(`f`)))
assert.Equal(t, `%!invalid(Num="-12.1")`, fmt.Sprintf("%d", Num(`"-12.1"`)))
})
t.Run("String", func(t *testing.T) {
for _, cc := range []struct {
Name string
Expand Down

0 comments on commit c56b7b7

Please sign in to comment.