Skip to content

Commit

Permalink
Add Float
Browse files Browse the repository at this point in the history
  • Loading branch information
sgreben committed Oct 3, 2018
1 parent 6958e18 commit e5da499
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
36 changes: 36 additions & 0 deletions floats.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,42 @@ import (
"strings"
)

// Float is a `flag.Value` for a float argument.
// The `BitSize` field is used for parsing when set.
type Float struct {
BitSize int

Value float64
Text string
}

// Help returns a string suitable for inclusion in a flag help message.
func (fv *Float) Help() string {
var bitSize string
if fv.BitSize != 0 {
bitSize = fmt.Sprintf("%d-bit ", fv.BitSize)
}
return fmt.Sprintf("a %sfloat", bitSize)
}

// Set is flag.Value.Set
func (fv *Float) Set(v string) error {
bitSize := fv.BitSize
if bitSize == 0 {
bitSize = 64
}
n, err := strconv.ParseFloat(v, bitSize)
if err == nil {
fv.Value = n
fv.Text = v
}
return err
}

func (fv *Float) String() string {
return fv.Text
}

// Floats is a `flag.Value` for float arguments.
// The `BitSize` field is used for parsing when set.
type Floats struct {
Expand Down
49 changes: 49 additions & 0 deletions floats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,55 @@ import (
"github.com/sgreben/flagvar"
)

func TestFloat(t *testing.T) {
fv := flagvar.Float{}
var fs flag.FlagSet
fs.Var(&fv, "float", "")

err := fs.Parse([]string{"-float", "1.5"})
if err != nil {
t.Fail()
}
if !reflect.DeepEqual(fv.Value, float64(1.5)) {
t.Fail()
}
}

func TestFloatHelp(t *testing.T) {
fv := flagvar.Float{BitSize: 64}
if !reflect.DeepEqual(fv.Help(), "a 64-bit float") {
t.Fail()
}
fv = flagvar.Float{BitSize: 32}
if !reflect.DeepEqual(fv.Help(), "a 32-bit float") {
t.Fail()
}
}

func TestFloatBitSize(t *testing.T) {
fv := flagvar.Float{BitSize: 64}
var fs flag.FlagSet
fs.Var(&fv, "float", "")

err := fs.Parse([]string{"-float", "1.234"})
if err != nil {
t.Fail()
}
if !reflect.DeepEqual(fv.Value, float64(1.234)) {
t.Fail()
}
}

func TestFloatFail(t *testing.T) {
fv := flagvar.Float{}
var fs flag.FlagSet
fs.Var(&fv, "float", "")

err := fs.Parse([]string{"-float", "abc"})
if err == nil {
t.Fail()
}
}
func TestFloats(t *testing.T) {
fv := flagvar.Floats{}
var fs flag.FlagSet
Expand Down

0 comments on commit e5da499

Please sign in to comment.