-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfloat.go
More file actions
83 lines (62 loc) · 1.25 KB
/
float.go
File metadata and controls
83 lines (62 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package nullish
import (
"bytes"
"database/sql/driver"
"errors"
"strconv"
"github.com/goccy/go-json"
)
type NullFloat struct {
Float float64
Valid bool
}
// Value method
func (nf NullFloat) Value() (driver.Value, error) {
if !nf.Valid {
return nil, nil
}
return nf.Float, nil
}
// Scan method
func (nf *NullFloat) Scan(value interface{}) error {
if value == nil {
nf.Float, nf.Valid = 0, false
return nil
}
switch t := value.(type) {
case float32:
nf.Float, nf.Valid = float64(t), true
case float64:
nf.Float, nf.Valid = t, true
case []byte:
f, err := strconv.ParseFloat(string(t), 64)
if err != nil {
return errors.New("type assertion []byte to float64 is failed")
}
nf.Float, nf.Valid = f, true
default:
return errors.New("type assertion to float64 is failed")
}
return nil
}
// MarshalJSON method
func (nf NullFloat) MarshalJSON() ([]byte, error) {
if !nf.Valid {
return NullType, nil
}
return json.Marshal(nf.Float)
}
// UnmarshalJSON method
func (nf *NullFloat) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, NullType) {
*nf = NullFloat{}
return nil
}
var res float64
err := json.Unmarshal(data, &res)
if err != nil {
return err
}
*nf = NullFloat{Float: res, Valid: true}
return nil
}