go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/experiments/cb-feed/pkg/price/price.go (about) 1 package price 2 3 import ( 4 "fmt" 5 "strconv" 6 ) 7 8 const priceBasis = 1000 9 10 // Parse pareses a price and returns the value. 11 func Parse(raw string) Price { 12 parsed, _ := strconv.ParseFloat(raw, 64) 13 return Price(parsed * priceBasis) 14 } 15 16 // Price is a fixed-point value that can represent prices 17 // and safely be used for math. 18 type Price int64 19 20 // Float64 returns a float64 form of the price 21 // by dividing the price by the basis. 22 func (p Price) Float64() float64 { 23 return float64(p) / float64(priceBasis) 24 } 25 26 // String returns a string form of the price. 27 func (p Price) String() string { 28 return fmt.Sprintf("%.2f", p.Float64()) 29 } 30 31 // Delta returns the absolute difference between 32 // a given price and another price. 33 func (p Price) Delta(other Price) Price { 34 if p > other { 35 return Price(p - other) 36 } 37 return Price(other - p) 38 } 39 40 // RightShift implements << for prices. 41 func (p Price) RightShift(by uint) Price { 42 return Price(p << by) 43 } 44 45 // LeftShift implements >> for prices. 46 func (p Price) LeftShift(by uint) Price { 47 return Price(p >> by) 48 } 49 50 // Add implements + for prices. 51 func (p Price) Add(other Price) Price { 52 return Price(p + other) 53 } 54 55 // Mul implements * for prices. 56 func (p Price) Mul(other Price) Price { 57 return Price((p * other) / priceBasis) 58 } 59 60 // Sub implements - for prices. 61 func (p Price) Sub(other Price) Price { 62 return Price(p - other) 63 } 64 65 // Div implements / for prices. 66 func (p Price) Div(other Price) Price { 67 return Price((p / other) * priceBasis) 68 }