Debian Codegraph @

execution/func_to_float.go

raw symbols SCIP
1 package execution
2
3 import (
4 "context"
5 "fmt"
6 "strconv"
7
8 "github.com/tomwright/dasel/v3/model"
9 )
10
11 // FuncToFloat is a function that converts the given value to a string.
12 var FuncToFloat = NewFunc(
13 "toFloat",
14 func(ctx context.Context, data *model.Value, args model.Values) (*model.Value, error) {
15 switch args[0].Type() {
16 case model.TypeString:
17 stringValue, err := args[0].StringValue()
18 if err != nil {
19 return nil, err
20 }
21
22 i, err := strconv.ParseFloat(stringValue, 64)
23 if err != nil {
24 return nil, err
25 }
26
27 return model.NewFloatValue(i), nil
28 case model.TypeInt:
29 i, err := args[0].IntValue()
30 if err != nil {
31 return nil, err
32 }
33 return model.NewFloatValue(float64(i)), nil
34 case model.TypeFloat:
35 return args[0], nil
36 case model.TypeBool:
37 i, err := args[0].BoolValue()
38 if err != nil {
39 return nil, err
40 }
41 if i {
42 return model.NewFloatValue(1), nil
43 }
44 return model.NewFloatValue(0), nil
45 default:
46 return nil, fmt.Errorf("cannot convert %s to float", args[0].Type())
47 }
48 },
49 ValidateArgsExactly(1),
50 )