MCPcopy Create free account
hub / github.com/amp-labs/connectors / AsFloat

Method AsFloat

common/stringMap.go:66–85  ·  view source on GitHub ↗

AsFloat is a helper function that extracts a float from the map. This function will convert number values such as int, uint, and float to float64. By doing so, it may lose precision for large numbers. This is helpful when you are not sure about the type of the number.

(key string)

Source from the content-addressed store, hash-verified

64// By doing so, it may lose precision for large numbers.
65// This is helpful when you are not sure about the type of the number.
66func (m StringMap) AsFloat(key string) (float64, error) {
67 val, err := m.Get(key)
68 if err != nil {
69 return 0, err
70 }
71
72 t := reflect.TypeOf(val)
73
74 //nolint:exhaustive
75 switch t.Kind() {
76 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
77 return float64(reflect.ValueOf(val).Int()), nil
78 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
79 return float64(reflect.ValueOf(val).Uint()), nil
80 case reflect.Float32, reflect.Float64:
81 return reflect.ValueOf(val).Float(), nil
82 default:
83 return 0, fmt.Errorf("%w: expected a number, but received %T", errNotANumber, val)
84 }
85}
86
87// AsInt is a helper function that extracts an integer from the map.
88// This function will convert number values such as int, uint, and float to int64.

Callers 1

TestStringMapFunction · 0.95

Calls 1

GetMethod · 0.95

Tested by 1

TestStringMapFunction · 0.76