-
Notifications
You must be signed in to change notification settings - Fork 0
/
decimal.go
66 lines (52 loc) · 1.21 KB
/
decimal.go
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
package util
import (
"database/sql/driver"
"errors"
"fmt"
"github.com/shopspring/decimal"
)
type Decimal decimal.Decimal
func (d Decimal) Unwrap() decimal.Decimal {
return decimal.Decimal(d)
}
func (d Decimal) String() string {
return decimal.Decimal(d).String()
}
func NewDecimalF(f float64) Decimal {
return Decimal(decimal.NewFromFloat(f))
}
func NewDecimal(s string) Decimal {
v, err := decimal.NewFromString(s)
Panic(err)
return Decimal(v)
}
func (d Decimal) MarshalJSON() ([]byte, error) {
return []byte(`"` + decimal.Decimal(d).String() + `"`), nil
}
func (d *Decimal) UnmarshalJSON(data []byte) error {
str := string(data)
if str == "null" {
return nil
}
if str[0] != '"' || str[len(str)-1] != '"' {
return errors.New("decimal value needs to be quote as string")
}
v, err := decimal.NewFromString(str[1 : len(str)-1])
if err != nil {
return err
}
*d = Decimal(v)
return nil
}
func (o *Decimal) Scan(value any) (err error) {
str, ok := value.(string)
if !ok {
return fmt.Errorf("cannot convert to string: %v, %T", value, value)
}
d, err := decimal.NewFromString(str)
*o = Decimal(d)
return
}
func (o Decimal) Value() (driver.Value, error) {
return decimal.Decimal(o).String(), nil
}