Skip to content
Open
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
11 changes: 11 additions & 0 deletions builtin/lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,17 @@ func Float(x any) any {
}
return f
default:
val := reflect.ValueOf(x)
switch val.Kind() {
case reflect.String:
return Float(val.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return float64(val.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return float64(val.Uint())
case reflect.Float32, reflect.Float64:
return val.Float()
}
panic(fmt.Sprintf("invalid operation: float(%T)", x))
}
}
Expand Down
23 changes: 23 additions & 0 deletions expr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3238,3 +3238,26 @@ func TestBytesLiteral_errors(t *testing.T) {
})
}
}

func TestFloatWithDefinedTypes(t *testing.T) {
type rate float32
type count uint16
type delta int64
type amount string
for _, tt := range []struct {
value any
want float64
}{
{rate(1.5), 1.5},
{count(512), 512},
{delta(-7), -7},
{amount("2.75"), 2.75},
} {
env := map[string]any{"value": tt.value}
program, err := expr.Compile("float(value)", expr.Env(env))
require.NoError(t, err)
got, err := expr.Run(program, env)
require.NoError(t, err)
require.Equal(t, tt.want, got)
}
}