float.go

 1package graphql
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"io"
 7	"strconv"
 8)
 9
10func MarshalFloat(f float64) Marshaler {
11	return WriterFunc(func(w io.Writer) {
12		io.WriteString(w, fmt.Sprintf("%g", f))
13	})
14}
15
16func UnmarshalFloat(v interface{}) (float64, error) {
17	switch v := v.(type) {
18	case string:
19		return strconv.ParseFloat(v, 64)
20	case int:
21		return float64(v), nil
22	case int64:
23		return float64(v), nil
24	case float64:
25		return v, nil
26	case json.Number:
27		return strconv.ParseFloat(string(v), 64)
28	default:
29		return 0, fmt.Errorf("%T is not an float", v)
30	}
31}