• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang decimal.Decimal类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/shopspring/decimal.Decimal的典型用法代码示例。如果您正苦于以下问题:Golang Decimal类的具体用法?Golang Decimal怎么用?Golang Decimal使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Decimal类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: genConvert

func (c *Converter) genConvert(value decimal.Decimal, from, to Currency, at *time.Time) (decimal.Decimal, error) {
	var t time.Time

	if at == nil {
		t = time.Now().UTC()
	} else {
		t = *at
	}

	var usd decimal.Decimal

	if from == USD {
		usd = value
	} else {
		fromRate, err := c.ex.Get(t, from)

		if err != nil {
			return decimal.Zero, err
		}

		usd = value.Mul(fromRate.ToUSD)
	}

	if to == USD {
		return usd, nil
	}

	toRate, err := c.ex.Get(t, to)

	if err != nil {
		return decimal.Zero, err
	}

	return usd.Mul(toRate.FromUSD), nil
}
开发者ID:simonz05,项目名称:currency,代码行数:35,代码来源:currency.go


示例2: toFloat64

//绝对值转成浮点数
func toFloat64(d decimal.Decimal) float64 {
	result, ok := d.Float64()
	if !ok {
		// TODO
	}
	return result
}
开发者ID:fishedee,项目名称:fishgo,代码行数:8,代码来源:math.go


示例3: Decode

//Decode is the inverse operation of Encode.
//Decode returns latitude, longitude, and whether or not they are both represented precisely as float64 types.
func Decode(bucket int64) (float64, float64, bool) {
	var latitudeUnshifted, longitudeUnshifted decimal.Decimal
	var latitude, longitude float64
	var err error
	var exact bool
	bucketString := strconv.FormatInt(bucket, 10)
	for len(bucketString) < 18 {
		bucketString = "0" + bucketString
	}

	latString, lonString := unzip(bucketString)
	latString = latString[0:3] + "." + latString[3:]
	lonString = lonString[0:3] + "." + lonString[3:]

	latitudeUnshifted, err = decimal.NewFromString(latString)
	longitudeUnshifted, err = decimal.NewFromString(lonString)
	if err != nil {
		fmt.Errorf("Error creating decimal from string")
	}
	latitudeUnshifted = latitudeUnshifted.Sub(decimal.NewFromFloat(90.0))
	longitudeUnshifted = longitudeUnshifted.Sub(decimal.NewFromFloat(180.0))
	latitude, exact = latitudeUnshifted.Float64()
	longitude, exact = longitudeUnshifted.Float64()
	return latitude, longitude, exact
}
开发者ID:nick11roberts,项目名称:geozip,代码行数:27,代码来源:geozip.go


示例4: DecimalToString

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()
}
开发者ID:gpahal,项目名称:calc,代码行数:7,代码来源:compute.go


示例5: Calculate

func (sc *salaryCalculator) Calculate(grossSalary, dependentsQty decimal.Decimal) Salary {
	inss := sc.inss.Calculate(grossSalary)
	dependents := sc.depedents.Calculate(dependentsQty)
	irrfBase := grossSalary.Sub(inss).Sub(dependents)
	irrf := sc.irrf.Calculate(irrfBase)
	netSalary := grossSalary.Sub(inss).Sub(irrf)
	return Salary{
		GrossSalary: grossSalary,
		INSS:        inss,
		Dependents:  dependents,
		IRRF:        irrf,
		NetSalary:   netSalary,
	}
}
开发者ID:thiagocaiubi,项目名称:isiro,代码行数:14,代码来源:salary.go


示例6: Calculate

func (irrf *IRRF) Calculate(grossSalary decimal.Decimal) decimal.Decimal {
	for _, irrfInterval := range irrf.irrfRange {
		if grossSalary.Cmp(irrfInterval.Lower) >= 0 && grossSalary.Cmp(irrfInterval.Upper) <= 0 {
			return grossSalary.Mul(irrfInterval.Aliquot).Sub(irrfInterval.Deduction)
		}
	}

	lastIRRFInterval := irrf.irrfRange[len(irrf.irrfRange)-1]

	return grossSalary.Mul(lastIRRFInterval.Aliquot).Sub(lastIRRFInterval.Deduction)
}
开发者ID:thiagocaiubi,项目名称:isiro,代码行数:11,代码来源:irrf.go


示例7: PlaceOrder

func (ex *CaVirtex) PlaceOrder(mode OrderMode, amount decimal.Decimal, price decimal.Decimal, base, counter string) (status, id string, err error) {
	textMode := "sell"
	if mode == ORDER_BUY {
		textMode = "buy"
	}

	resp, err := ex.AuthenticatedPost("order", map[string]string{
		"currencypair": fmt.Sprintf("%s%s", base, counter),
		"mode":         textMode,
		"amount":       amount.String(),
		"price":        price.String(),
	})
	if err != nil {
		return "", "", err
	}

	result := struct {
		Status  string
		Message string
		ApiRate int
		Order   struct {
			Status string
			ID     int
		}
	}{}

	cnt, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", "", err
	}

	err = json.Unmarshal(cnt, &result)
	if err != nil {
		return "", "", err
	}

	if result.Status != "ok" {
		return "", "", fmt.Errorf("status=%s: %s", result.Status, result.Message)
	}

	return result.Order.Status, fmt.Sprintf("%d", result.Order.ID), nil
}
开发者ID:abourget,项目名称:goexchanges,代码行数:42,代码来源:orders.go


示例8: TestConnQueryDatabaseSQLDriverValuer

// Use github.com/shopspring/decimal as real-world database/sql custom type
// to test against.
func TestConnQueryDatabaseSQLDriverValuer(t *testing.T) {
	t.Parallel()

	conn := mustConnect(t, *defaultConnConfig)
	defer closeConn(t, conn)

	expected, err := decimal.NewFromString("1234.567")
	if err != nil {
		t.Fatal(err)
	}
	var num decimal.Decimal

	err = conn.QueryRow("select $1::decimal", expected).Scan(&num)
	if err != nil {
		t.Fatalf("Scan failed: %v", err)
	}

	if !num.Equals(expected) {
		t.Errorf("Expected num to be %v, but it was %v", expected, num)
	}

	ensureConnValid(t, conn)
}
开发者ID:yunhor,项目名称:pgx,代码行数:25,代码来源:query_test.go


示例9: Quote

func Quote(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	StockId := vars["symbol"]
	UserId := vars["id"]
	TransId := r.Header.Get("X-TransNo")
	if TransId == "" {
		TransId = "0"
	}

	//Audit UserCommand
	Guid := getNewGuid()
	CommandEvent := UserCommandEvent{
		EventType:     "UserCommandEvent",
		Guid:          Guid.String(),
		OccuredAt:     time.Now(),
		TransactionId: TransId,
		UserId:        UserId,
		Service:       "Command",
		Server:        "B134",
		Command:       "QUOTE",
		StockSymbol:   StockId,
		Funds:         "",
	}
	SendRabbitMessage(CommandEvent, CommandEvent.EventType)

	//Check Stock Symbol
	if len(StockId) == 0 || len(StockId) > 3 {
		writeResponse(w, http.StatusBadRequest, "Symbol is Not Valid")
		return
	}

	//Get Stock Price
	var strPrice string
	strPrice, _ = getStockPrice(TransId, "false", UserId, StockId, Guid.String())

	//Verify Return Price
	var price decimal.Decimal
	price, err := decimal.NewFromString(strPrice)
	if err != nil {
		writeResponse(w, http.StatusBadRequest, "Quote Return: "+err.Error())
		return
	}

	//Success
	var Output string = "The Quote For UserId " + UserId + " and StockId " + StockId + " returned " + price.String()
	writeResponse(w, http.StatusOK, Output)
}
开发者ID:sjlbos,项目名称:SENG462_DTS,代码行数:47,代码来源:quote.go


示例10: Calculate

func (inss *INSS) Calculate(grossSalary decimal.Decimal) decimal.Decimal {
	for _, inssInterval := range inss.inssRange {
		if grossSalary.Cmp(inssInterval.Lower) >= 0 && grossSalary.Cmp(inssInterval.Upper) <= 0 {
			return grossSalary.Mul(inssInterval.Aliquot)
		}
	}

	lastINSSInterval := inss.inssRange[len(inss.inssRange)-1]

	return lastINSSInterval.Upper.Mul(lastINSSInterval.Aliquot)
}
开发者ID:thiagocaiubi,项目名称:isiro,代码行数:11,代码来源:inss.go


示例11: Sell

func Sell(w http.ResponseWriter, r *http.Request) {
	zero, _ := decimal.NewFromString("0")
	type sell_struct struct {
		Amount string
		Symbol string
	}

	type return_struct struct {
		Error      bool
		SaleId     int
		Price      string
		NumShares  int64
		Expiration time.Duration
	}

	vars := mux.Vars(r)
	UserId := vars["id"]
	TransId := r.Header.Get("X-TransNo")
	if TransId == "" {
		TransId = "0"
	}

	//Decode Body
	decoder := json.NewDecoder(r.Body)
	var t sell_struct
	err := decoder.Decode(&t)

	//Audit UserCommand
	Guid := getNewGuid()
	OccuredAt := time.Now()
	CommandEvent := UserCommandEvent{
		EventType:     "UserCommandEvent",
		Guid:          Guid.String(),
		OccuredAt:     OccuredAt,
		TransactionId: TransId,
		UserId:        UserId,
		Service:       "Command",
		Server:        Hostname,
		Command:       "SELL",
		StockSymbol:   t.Symbol,
		Funds:         t.Amount,
	}
	SendRabbitMessage(CommandEvent, CommandEvent.EventType)
	if err != nil {
		writeResponse(w, http.StatusBadRequest, err.Error())
		return
	}

	//get User Account Information
	db, id, found, _ := getDatabaseUserId(UserId)
	if found == false {
		writeResponse(w, http.StatusOK, "User Account Does Not Exist")
		return
	}

	//Check amount
	AmountDec, err := decimal.NewFromString(t.Amount)
	if err != nil {
		writeResponse(w, http.StatusBadRequest, err.Error())
		return
	}
	if AmountDec.Cmp(zero) != 1 {
		writeResponse(w, http.StatusBadRequest, "Amount to sell is not a valid number")
		return
	}

	//Check Stock Symbol
	StockId := t.Symbol
	if len(StockId) == 0 || len(StockId) > 3 {
		writeResponse(w, http.StatusBadRequest, "Symbol is Not Valid")
		return
	}

	//Get and Verify Quote
	var strPrice string
	var strExpiration string
	strPrice, strExpiration = getStockPrice(TransId, "true", UserId, StockId, 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
	}
	//Verify Expiration Time
	ExpirationTime, err := time.Parse("2006-01-02 15:04:05 -0700 MST", strExpiration)
	if err != nil {
		writeResponse(w, http.StatusOK, "Expiration Conversion Error")
		return
	}

	//Calculate Amount to Sell
	toSell := (AmountDec.Div(quotePrice)).IntPart()
	if toSell < 1 {
		writeResponse(w, http.StatusOK, "Can't Sell less than 1 Stock")
		return
	}
//.........这里部分代码省略.........
开发者ID:sjlbos,项目名称:SENG462_DTS,代码行数:101,代码来源:sell.go


示例12: GetFormattedAmount

func (a *Account) GetFormattedAmount(amount decimal.Decimal) string {
	return amount.StringFixed(a.DecimalPlaces)
}
开发者ID:yendor,项目名称:lunchmoney,代码行数:3,代码来源:account.go


示例13: handleConnection

func handleConnection(conn net.Conn) {
	var found bool
	var QuoteItem QuoteCacheItem
	if err != nil {
		// do stuff
		return
	}
	status := make([]byte, 100)
	_, err = conn.Read(status)
	if err != nil {
		// do stuff
		println("ERROR READ: " + err.Error())
		return
	}

	status = bytes.Trim(status, "\x00")

	inputs := strings.Split(string(status), ",")

	var price decimal.Decimal

	_, err := strconv.ParseBool(strings.ToLower(inputs[0]))
	APIUserId := inputs[1]
	stockSymbol := inputs[2]
	TransId := "1"
	GGuid := getNewGuid()
	Guid := GGuid.String()
	if len(inputs) > 3 {
		TransId = inputs[3]
		Guid = inputs[4]
	}

	QuoteItem, found = memCache[stockSymbol]
	if found {
		if QuoteItem.Expiration.After(time.Now()) {
			fmt.Fprintf(conn, string(QuoteItem.Value)+","+QuoteItem.Expiration.String())
			conn.Close()
			hit = hit + 1
			return
		} else {
			found = false
		}
	}
	miss = miss + 1
	if !found {
		messages := make(chan string)
		var returned bool = false
		num_threads := 0

		go func() {
			for returned == false {
				num_threads = num_threads + 1
				go func() {
					sendString := stockSymbol + "," + APIUserId + "\n"
					addr, err := net.ResolveTCPAddr("tcp", "quoteserve.seng.uvic.ca:"+quotePort)
					if err != nil {
						return
					}
					qconn, err := net.DialTCP("tcp", nil, addr)
					if err != nil {
						//error
						println("ERROR qconn: " + err.Error())
						return
					}
					defer qconn.Close()
					_, err = fmt.Fprintf(qconn, sendString)
					if err != nil {
						failOnError(err, "Error with fprintf")
					}
					response := make([]byte, 100)
					_, err = qconn.Read(response)
					returned = true
					messages <- string(response)
				}()
				time.Sleep(time.Duration(thread_wait) * time.Millisecond)
			}
		}()

		QuoteReturn := <-messages
		ParsedQuoteReturn := strings.Split(QuoteReturn, ",")
		price, err = decimal.NewFromString(ParsedQuoteReturn[0])
		if err != nil {
			//error
			println("ERROR PARSING")
		}

		backoff := 50 + rand.Intn(5)
		QuoteExpiration := time.Now().Add(time.Duration(backoff) * time.Second)

		_, err = conn.Write([]byte(price.String() + "," + QuoteExpiration.String()))
		conn.Close()
		stockSymbol = ParsedQuoteReturn[1]
		ReturnUserId := ParsedQuoteReturn[2]
		msTimeStamp, err := msToTime(ParsedQuoteReturn[3])
		if err != nil {
			//error

		}
		cryptoKey := stripCtlAndExtFromUTF8(ParsedQuoteReturn[4])
		cryptoKey = strings.TrimSpace(cryptoKey)
//.........这里部分代码省略.........
开发者ID:sjlbos,项目名称:SENG462_DTS,代码行数:101,代码来源:main.go


示例14: MultiplyDecimalWithoutNew

func MultiplyDecimalWithoutNew(decimalStartFloat, decimalFactor decimal.Decimal) (calculated decimal.Decimal) {
	calculated = decimalStartFloat.Mul(decimalFactor)

	return
}
开发者ID:Zumata,项目名称:benchmark,代码行数:5,代码来源:decimal.go


示例15: newton

func newton(z, x decimal.Decimal) decimal.Decimal {
	return z.Sub(z.Mul(z).Sub(x).Div(Const2.Mul(z)))
}
开发者ID:fernandosanchezjr,项目名称:gotsp,代码行数:3,代码来源:sqrt.go


示例16: AddDecimalWithoutNew

func AddDecimalWithoutNew(decimalStartFloat, decimalFactor decimal.Decimal) (calculated decimal.Decimal) {
	calculated = decimalStartFloat.Add(decimalFactor)

	return
}
开发者ID:Zumata,项目名称:benchmark,代码行数:5,代码来源:decimal.go


示例17: Calculate

func (f fakeCalculator) Calculate(d decimal.Decimal) decimal.Decimal {
	return d.Mul(rebatePercentage)
}
开发者ID:thiagocaiubi,项目名称:isiro,代码行数:3,代码来源:salary_test.go


示例18: ConvertToDecimalBinary

func ConvertToDecimalBinary(f func(float64, float64) float64, a decimal.Decimal, b decimal.Decimal) decimal.Decimal {
	aFloat, _ := a.Float64()
	bFloat, _ := b.Float64()

	return decimal.NewFromFloat(f(aFloat, bFloat))
}
开发者ID:gpahal,项目名称:calc,代码行数:6,代码来源:operators.go


示例19: isNegativeDecimal

// isPositiveDecimal checks if the decimal is positive
func isNegativeDecimal(amount decimal.Decimal) bool {
	return amount.Cmp(decimal.NewFromFloat(0)) < 0
}
开发者ID:Hinton,项目名称:go-learn,代码行数:4,代码来源:account.go


示例20: UpdateSale

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
}
开发者ID:sjlbos,项目名称:SENG462_DTS,代码行数:82,代码来源:sell.go



注:本文中的github.com/shopspring/decimal.Decimal类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang buslogic.AdminLogic类代码示例发布时间:2022-05-28
下一篇:
Golang decimal.NewFromString函数代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap