/
price.go
69 lines (58 loc) · 1.2 KB
/
price.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
67
68
69
package txnbuild
import (
"strconv"
pricepkg "github.com/diamcircle/go/price"
"github.com/diamcircle/go/support/errors"
"github.com/diamcircle/go/xdr"
)
type price struct {
n int
d int
s string
}
func (p *price) parse(s string) error {
if len(s) == 0 {
return errors.New("cannot parse price from empty string")
}
xdrPrice, err := pricepkg.Parse(s)
if err != nil {
return errors.Wrap(err, "failed to parse price from string")
}
if len(p.s) > 0 {
inverse, err := pricepkg.Parse(p.s)
if err == nil && xdrPrice == inverse {
return nil
}
}
p.n = int(xdrPrice.N)
p.d = int(xdrPrice.D)
p.s = s
return nil
}
func (p *price) fromXDR(xdrPrice xdr.Price) {
n := int(xdrPrice.N)
d := int(xdrPrice.D)
if n == p.n && d == p.d {
return
}
p.n = n
p.d = d
v := float64(n) / float64(d)
// The special precision -1 uses the smallest number of digits
// necessary such that ParseFloat will return f exactly.
p.s = strconv.FormatFloat(v, 'f', -1, 32)
}
func priceFromXDR(xdrPrice xdr.Price) price {
var p price
p.fromXDR(xdrPrice)
return p
}
func (p price) string() string {
return p.s
}
func (p price) toXDR() xdr.Price {
return xdr.Price{
N: xdr.Int32(p.n),
D: xdr.Int32(p.d),
}
}