func TestFIXDecimalRead(t *testing.T) { var tests = []struct { bytes string expected decimal.Decimal expectError bool }{ {bytes: "15", expected: decimal.New(15, 0)}, {bytes: "15.000", expected: decimal.New(15, 0)}, {bytes: "15.001", expected: decimal.New(15001, -3)}, {bytes: "-15.001", expected: decimal.New(-15001, -3)}, {bytes: "blah", expectError: true}, {bytes: "+200.00", expected: decimal.New(200, 0)}, } for _, test := range tests { var field FIXDecimal err := field.Read([]byte(test.bytes)) require.Equal(t, test.expectError, err != nil) if !test.expectError { assert.True(t, test.expected.Equals(field.Decimal), "Expected %s got %s", test.expected, field.Decimal) } } }
func Example_orders() { virtex := &CaVirtex{ APIKey: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", APIToken: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", } status, id, err := virtex.PlaceOrder( cavirtex.ORDER_SELL, decimal.New(5, -2), decimal.New(1, 3), "BTC", "CAD", ) if err != nil { log.Println("Error placing order:", err) os.Exit(1) } fmt.Println("Got order reply, status:", status, "id:", id) time.Sleep(1 * time.Second) err = virtex.CancelOrder(id) if err != nil { log.Println("Error canceling order:", err) } fmt.Println("Canceled order", id) }
func DecimalToString(res decimal.Decimal, min int32, max int32) string { if res.Cmp(decimal.New(10, min)) <= 0 || res.Cmp(decimal.New(10, max)) >= 0 { f, _ := res.Float64() return strconv.FormatFloat(f, 'G', -1, 64) } return res.String() }
func Parse(s string) (time.Duration, error) { var d time.Duration var p parser if s == "0" { return d, nil } if s[len(s)-1] == 's' { switch c := s[len(s)-2]; c { case 'n': //ns p = parsers[0] case 'µ': //µs p = parsers[1] case 'm': //ms p = parsers[2] default: if '0' <= c && c <= '9' { //s p = parsers[3] } else { return d, ErrMalformed } } } else { return d, ErrMalformed } sub := p.re.FindStringSubmatch(s) // fmt.Println(len(sub), sub) switch len(sub) { case 5: i, _ := strconv.Atoi(sub[2]) d += time.Duration(i) * time.Hour i, _ = strconv.Atoi(sub[3]) d += time.Duration(i) * time.Minute f, err := decimal.NewFromString(sub[4]) if err != nil { panic(err) } f = f.Mul(decimal.New(int64(p.unit), 0)) d += time.Duration(f.IntPart()) case 3: f, err := decimal.NewFromString(sub[2]) if err != nil { panic(err) } f = f.Mul(decimal.New(int64(p.unit), 0)) d += time.Duration(f.IntPart()) default: return d, ErrMalformed } if sub[1] != "-" { return d, nil } else { return -d, nil } }
func main() { counter := decimal.New(0, 0) inc := decimal.New(1, -2) fmt.Println("Increment: ", inc) for i := 0; i < 1000; i++ { counter = counter.Add(inc) } fmt.Println("Total: ", counter) counter = counter.Add(decimal.New(1, 16)) fmt.Println("Total: ", counter) counter = counter.Add(decimal.New(1, -10)) fmt.Println("Total: ", counter) }
func TestFIXDecimalWrite(t *testing.T) { var tests = []struct { decimal FIXDecimal expected string }{ {decimal: FIXDecimal{Decimal: decimal.New(-1243456, -4), Scale: 4}, expected: "-124.3456"}, {decimal: FIXDecimal{Decimal: decimal.New(-1243456, -4), Scale: 5}, expected: "-124.34560"}, {decimal: FIXDecimal{Decimal: decimal.New(-1243456, -4), Scale: 0}, expected: "-124"}, } for _, test := range tests { b := test.decimal.Write() assert.Equal(t, test.expected, string(b)) } }
// Scan populates `row` from `ent`. func (row *Payment) Scan(ent entity.Payment) (err error) { row.PagingToken = ent.PagingToken row.From = string(ent.From) row.To = string(ent.To) row.Memo.Scan(ent.Memo) row.Asset.Scan(ent.Asset) row.Amount = ent.Amount.Mul(decimal.New(1, 7)).IntPart() return }
func (s *Share) GetValue() { // 15-min delayed full quote for Apple. q, err := finance.GetQuote(s.Code) if err != nil { log.Println(q) } qty := decimal.New(s.Qty, 0) s.Value = q.LastTradePrice.Mul(qty) }
func powInt(d decimal.Decimal, n int) decimal.Decimal { tmp := n res := decimal.New(1, 0) factor := d for tmp > 0 { if (tmp % 2) == 1 { res = res.Mul(factor) } tmp /= 2 factor = factor.Mul(factor) } return res }
func UpdateSale(w http.ResponseWriter, r *http.Request) { zero, _ := decimal.NewFromString("0") vars := mux.Vars(r) UserId := vars["id"] TransId := vars["PurchaseId"] //get User Account Information db, uid, found, _ := getDatabaseUserId(UserId) if found == false { writeResponse(w, http.StatusOK, "User Account Does Not Exist") return } Guid := getNewGuid() //Find last Sell Command LatestPendingrows, err := db.Query(getLatestPendingSale, uid) defer LatestPendingrows.Close() if err != nil { writeResponse(w, http.StatusOK, "Error Getting Last Sale: "+err.Error()) return } var id string var stock string var num_shares int var share_price string var requested_at time.Time var expires_at time.Time found = false for LatestPendingrows.Next() { found = true err = LatestPendingrows.Scan(&id, &uid, &stock, &num_shares, &share_price, &requested_at, &expires_at) } if found == false { writeResponse(w, http.StatusOK, "No Recent Sell Commands") return } strOldPrice := strings.TrimPrefix(share_price, "$") strOldPrice = strings.Replace(strOldPrice, ",", "", -1) OldPrice, err := decimal.NewFromString(strOldPrice) if err != nil { writeResponse(w, http.StatusBadRequest, err.Error()+strOldPrice) return } //Get and Verify Quote var strPrice string strPrice, _ = getStockPrice(TransId, "true", UserId, stock, Guid.String()) var quotePrice decimal.Decimal quotePrice, err = decimal.NewFromString(strPrice) if err != nil { writeResponse(w, http.StatusBadRequest, err.Error()) return } if quotePrice.Cmp(zero) != 1 { writeResponse(w, http.StatusBadRequest, "Quote is not a valid number") return } totalAmount := decimal.New(int64(num_shares), 0).Mul(OldPrice) newShareNum := totalAmount.Div(quotePrice).IntPart() diffShares := int(newShareNum) - num_shares _, err = db.Exec(updateSale, TransId, int(newShareNum), strPrice, int(diffShares), time.Now().Add(time.Duration(60)*time.Second)) if err != nil { writeResponse(w, http.StatusBadRequest, "Unable to update Sale") return } type return_struct struct { Error bool SaleId string Price string NumShares int64 Expiration time.Duration } //Build Response rtnStruct := return_struct{false, id, strPrice, newShareNum, -1} strRtnStruct, err := json.Marshal(rtnStruct) writeResponse(w, http.StatusOK, string(strRtnStruct)) return }
package functions import ( "math" "github.com/gpahal/calc/operators" "github.com/shopspring/decimal" ) var ( one = decimal.New(1, 0) sin = &operators.Operator{ Name: "sin", Precedence: 0, Associativity: operators.L, Args: 1, Operation: func(args []decimal.Decimal) decimal.Decimal { return operators.ConvertToDecimalUnary(math.Sin, args[0]) }, } cos = &operators.Operator{ Name: "cos", Precedence: 0, Associativity: operators.L, Args: 1, Operation: func(args []decimal.Decimal) decimal.Decimal { return operators.ConvertToDecimalUnary(math.Cos, args[0]) }, }
func setupPerson() ([]*Period, []*Person, []*Customer, []*CusRank, []*Employee) { pr := make([]*Period, 12) pr[0] = &Period{Year: 2015, Month: 1} pr[1] = &Period{Year: 2015, Month: 2} pr[2] = &Period{Year: 2015, Month: 3} pr[3] = &Period{Year: 2015, Month: 4} pr[4] = &Period{Year: 2015, Month: 5} pr[5] = &Period{Year: 2015, Month: 6} pr[6] = &Period{Year: 2015, Month: 7} pr[7] = &Period{Year: 2015, Month: 8} pr[8] = &Period{Year: 2015, Month: 9} pr[9] = &Period{Year: 2015, Month: 10} pr[10] = &Period{Year: 2015, Month: 11} pr[11] = &Period{Year: 2015, Month: 12} ps := make([]*Person, 5) loc, _ := time.LoadLocation("Asia/Bangkok") ps[0] = &Person{FName: "เกษม", LName: "อานนทวิลาศ", NName: "Tom", BDate: time.Date(1974, time.October, 4, 0, 0, 0, 0, loc)} ps[1] = &Person{FName: "จิราภรณ์", LName: "อานนทวิลาศ", NName: "Jip", BDate: time.Date(1976, time.August, 12, 0, 0, 0, 0, time.Local)} ps[2] = &Person{FName: "ทนัฐพร", LName: "อานนทวิลาศ", NName: "Tim", BDate: time.Date(1976, time.August, 31, 0, 0, 0, 0, time.Local)} ps[3] = &Person{FName: "ธนันท์", LName: "อานนทวิลาศ", NName: "Tam", BDate: time.Date(1974, time.June, 7, 0, 0, 0, 0, time.Local)} ps[4] = &Person{FName: "สาธิต", LName: "โฉมวัฒนา", NName: "น้อย", BDate: time.Date(1974, time.June, 10, 0, 0, 0, 0, time.Local)} c := make([]*Customer, 5) c[0] = &Customer{CusType: COMPANY, Contact: ps[0], Name: "Dummy Customer", debit: decimal.Zero, credit: decimal.Zero} c[1] = &Customer{CusType: COMPANY, Contact: nil, Name: "บจก.เชียงใหม่คอนสตรัคชั่น"} c[2] = &Customer{CusType: COMPANY, Contact: nil, Name: "บจก.ปาล์ม การ์เด้น เชียงใหม่"} c[3] = &Customer{CusType: COMPANY, Contact: nil, Name: "บริษัท ส.เต็งไตรรัตน์(น่าน) จำกัด"} cr := make([]*CusRank, 5) cr[0] = &CusRank{Period: pr[0], Customer: c[0], Rank: A, KI1Continous: 4, KI2PaymentDue: 4, KI3Responsibility: 4, KI4Charactor: 4} cr[1] = &CusRank{Period: pr[0], Customer: c[1], Rank: A, KI1Continous: 4, KI2PaymentDue: 4, KI3Responsibility: 4, KI4Charactor: 4} cr[2] = &CusRank{Period: pr[0], Customer: c[2], Rank: A, KI1Continous: 4, KI2PaymentDue: 4, KI3Responsibility: 4, KI4Charactor: 4} cr[3] = &CusRank{Period: pr[0], Customer: c[3], Rank: A, KI1Continous: 4, KI2PaymentDue: 4, KI3Responsibility: 4, KI4Charactor: 4} cr[4] = &CusRank{Period: pr[0], Customer: c[4], Rank: A, KI1Continous: 4, KI2PaymentDue: 4, KI3Responsibility: 4, KI4Charactor: 4} tt := make([]*Title, 7) tt[0] = &Title{TH: "ประธานกรรมการ", EN: "Board of Director"} tt[1] = &Title{Parent: tt[0], TH: "รองประธานกรรมการ", EN: "Director"} tt[2] = &Title{Parent: tt[1], TH: "กรรมการผู้จัดการ", EN: "Managing Director"} tt[3] = &Title{Parent: tt[2], TH: "ผู้อำนวยการขาย", EN: "Sales Director"} tt[4] = &Title{Parent: tt[2], TH: "ผู้อำนวยการบริหารสินค้า", EN: "Merchandise Director"} tt[5] = &Title{Parent: tt[3], TH: "พนักงานขาย", EN: "Sales"} fmt.Println("Title") emp := make([]*Employee, 5) emp[0] = &Employee{Person: ps[0], Title: tt[2], Code: "39001", salary: decimal.New(40000, 0)} emp[1] = &Employee{Person: ps[1], Title: tt[3], Code: "48001", salary: decimal.New(30000, 0)} emp[2] = &Employee{Person: ps[2], Title: tt[4], Code: "49001", salary: decimal.New(20000, 0)} emp[3] = &Employee{Person: ps[3], Title: tt[4], Code: "50001", salary: decimal.New(20000, 0)} emp[4] = &Employee{Person: ps[4], Title: tt[5], Code: "53001", salary: decimal.New(9000, 0)} fmt.Println("Employee") o := make([]*Org, 20) o[0] = &Org{TH: "สำนักกรรมการผู้จัดการ", EN: "Managing Director Office", Short: "MD"} o[1] = &Org{Parent: o[0], TH: "ขาย", EN: "Sales", Short: "SA"} o[2] = &Org{Parent: o[1], TH: "หน้าร้านสาขา 1", EN: "Retail Store 1", Short: "S1"} o[3] = &Org{Parent: o[1], TH: "หน้าร้านสาขา 2", EN: "Retail Store 2", Short: "S2"} o[4] = &Org{Parent: o[1], TH: "โครงการ 1", EN: "Project1", Short: "PJ1"} o[5] = &Org{Parent: o[1], TH: "โครงการ 2", EN: "Project2", Short: "PJ2"} o[6] = &Org{Parent: o[1], TH: "ค้าส่ง", EN: "Wholesales", Short: "WS"} o[7] = &Org{Parent: o[0], TH: "บริหารสินค้า", EN: "Merchandising", Short: "MC"} o[8] = &Org{Parent: o[7], TH: "แผนกสินค้า1", EN: "Category1", Short: "CAT1"} o[9] = &Org{Parent: o[7], TH: "แผนกสินค้า2", EN: "Category2", Short: "CAT2"} o[10] = &Org{Parent: o[7], TH: "แผนกสินค้า1", EN: "Category1", Short: "CAT3"} o[11] = &Org{Parent: o[7], TH: "แผนกสินค้า4", EN: "Category4", Short: "CAT4"} o[12] = &Org{Parent: o[7], TH: "การตลาด", EN: "Marketing", Short: "CAT4"} o[13] = &Org{Parent: o[7], TH: "พัฒนาระบบคุณภาพ", EN: "Quality Management Development", Short: "QMD"} o[14] = &Org{Parent: o[7], TH: "พัฒนาระบบสาขา", EN: "Business Development", Short: "QMD"} o[15] = &Org{Parent: o[7], TH: "พัฒนาระบบบริการลูกค้า", EN: "Customer Service Development", Short: "CSD"} o[16] = &Org{Parent: o[7], TH: "Information Technology", EN: "Information Technology", Short: "IT"} return pr, ps, c, cr, emp }
"-3^2": StringToDecimal("-9"), "2(1+1)4": StringToDecimal("16"), "3*abs(1-5)": StringToDecimal("12"), "ln(3^15)": StringToDecimal("16.47918433"), "sqrt(10)": StringToDecimal("3.16227766"), "abs(-3/2)": StringToDecimal("1.5"), "1+2sin(-1024)tan(acos(1))^2": StringToDecimal("1"), "tan(10)cos(20)": StringToDecimal("0.2645844"), "2(e^3)": StringToDecimal("40.1710738464"), "sin(pi*π)": StringToDecimal("-0.430301217"), "3π": StringToDecimal("9.42477796"), "0.1+0.2": StringToDecimal("0.3"), "(0.1+0.4)^5": StringToDecimal("0.03125"), } var DELTA = decimal.New(1, -6) func StringToDecimal(str string) decimal.Decimal { d, err := decimal.NewFromString(str) if err != nil { panic(err) } return d } func TestEvaluate(t *testing.T) { for expression, expected := range exps { res, err := Evaluate(expression) if err != nil { t.Error(err) } else if res.Sub(expected).Abs().Cmp(DELTA) > 0 {