当前位置: 首页>>代码示例>>Golang>>正文


Golang decimal.NewFromString函数代码示例

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


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

示例1: 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

示例2: Parse

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
	}
}
开发者ID:zzn01,项目名称:duration,代码行数:59,代码来源:duration.go

示例3: AccountsUpdater

func AccountsUpdater(c *gin.Context) {
	acc_id, err := strconv.ParseInt(c.Param("accountId"), 10, 64)
	if err != nil {
		log.Fatal(err)
	}

	trans_id, err := strconv.ParseInt(c.PostForm("ID"), 10, 64)
	if err != nil {
		log.Printf("Invalid ID: %v - %v\n", trans_id, err)
		return
	}

	var account *Account
	for _, acc := range accounts {
		if acc.ID == acc_id {
			account = acc
			break
		}
	}

	var transaction Transaction
	for _, trans := range account.Transactions {
		if trans.ID == trans_id {
			transaction = trans
		}
	}

	transaction.Payee = c.PostForm("Payee")
	transaction.Memo = c.PostForm("Memo")
	debit, err := decimal.NewFromString(c.PostForm("Debit"))
	if err != nil {
		log.Printf("Invalid Debit %v\n", err)
	} else {
		transaction.Debit = debit
	}
	credit, err := decimal.NewFromString(c.PostForm("Credit"))
	if err != nil {
		log.Printf("Invalid Credit %v\n", err)
	} else {
		transaction.Credit = credit
	}

	for trans_key, trans := range account.Transactions {
		if trans.ID == trans_id {
			account.Transactions[trans_key] = transaction

			jsonResponse, err := json.Marshal(transaction)
			if err != nil {
				log.Printf("Json marshaling error: %v\n", err)
				return
			}
			c.JSON(http.StatusOK, jsonResponse)
		}
	}
}
开发者ID:yendor,项目名称:lunchmoney,代码行数:55,代码来源:account.go

示例4: Money

func Money(value interface{}, code string) (MoneyObject, error) {
	currency, found := CurrencyTypes[code]
	if !found {
		return MoneyObject{}, errors.New("Code not found.")
	}

	var money decimal.Decimal
	var moneyObject MoneyObject

	switch v := value.(type) {
	case string:
		m, err := decimal.NewFromString(v)
		if err != nil {
			return MoneyObject{}, err
		}
		money = m
	case float32:
		money = decimal.NewFromFloat(float64(v))
	case float64:
		money = decimal.NewFromFloat(v)
	case int:
		money = decimal.NewFromFloat(float64(v))
	default:
		return MoneyObject{}, errors.New("Value could not be translated.")
	}

	moneyObject.money = money
	moneyObject.currency = currency

	return moneyObject, nil
}
开发者ID:stints,项目名称:gocurrency,代码行数:31,代码来源:currency.go

示例5: parseDecimal

func parseDecimal(lit string) (decimal.Decimal, error) {
	f, err := decimal.NewFromString(lit)
	if err != nil {
		return decimal.Zero, errors.New("Cannot parse recognized decimal: " + lit)
	}
	return f, nil
}
开发者ID:gpahal,项目名称:calc,代码行数:7,代码来源:compute.go

示例6: StringToDecimal

func StringToDecimal(str string) decimal.Decimal {
	d, err := decimal.NewFromString(str)
	if err != nil {
		panic(err)
	}
	return d
}
开发者ID:gpahal,项目名称:calc,代码行数:7,代码来源:compute_test.go

示例7: TestTransactions

func TestTransactions(t *testing.T) {

	a := &Account{IsActive: true, CurrencyCode: "AUD"}

	credit10, _ := decimal.NewFromString("10.0")
	debit, _ := decimal.NewFromString("0.0")

	trans := Transaction{
		Credit:    credit10,
		Debit:     debit,
		IsCleared: true,
	}

	a.AddTransaction(trans)

	total := a.GetTotal()

	if total.String() != credit10.String() {
		t.Errorf("Total not right, expected %v got %v", credit10, a.GetTotal())
	}
	if a.GetClearedTotal().String() != credit10.String() {
		t.Error("Cleared Total not right")
	}

	credit, _ := decimal.NewFromString("0.0")
	debit, _ = decimal.NewFromString("5.0")

	trans.Credit = credit
	trans.Debit = debit
	trans.IsCleared = false
	a.AddTransaction(trans)

	if a.GetTotal().String() != debit.String() {
		t.Error("Total not right")
	}

	if a.GetClearedTotal().String() != credit10.String() {
		t.Error("Cleared total not right")
	}

	tr := a.GetTransactions()

	if len(tr) != 2 {
		t.Error("Number of transactions not right")
	}
	// log.Printf("%v\n", tr)
}
开发者ID:yendor,项目名称:lunchmoney,代码行数:47,代码来源:account_test.go

示例8: queryDecimal

func queryDecimal(fieldName string) decimal.Decimal {
	val, err := decimal.NewFromString(queryString(fieldName))
	if err != nil {
		panic(err)
	}

	return val
}
开发者ID:quickfixgo,项目名称:examples,代码行数:8,代码来源:console.go

示例9: NewNum

// NewNum initializes a Num from a BasicLit. Kind will hold the unit
// the number portion is always treated as a float.
func NewNum(lit *ast.BasicLit) (*Num, error) {
	val := lit.Value
	// TODO: scanner should remove unit
	kind := lit.Kind
	val = strings.TrimSuffix(lit.Value, token.Tokens[kind])
	dec, err := decimal.NewFromString(val)
	return &Num{dec: dec, Unit: unitLookup(kind)}, err
}
开发者ID:wellington,项目名称:sass,代码行数:10,代码来源:convert.go

示例10: ImportTransactions

func (a *Account) ImportTransactions(r io.Reader) {

	csvr := csv.NewReader(r)
	csvr.LazyQuotes = true
	csvr.TrimLeadingSpace = true

	records, err := csvr.ReadAll()
	if err != nil {
		log.Println(err)
	}

	for k, record := range records {
		if k == 0 {
			continue
		}

		transDate, err := time.Parse("02/01/2006", record[1])
		if err != nil {
			log.Println(err)
		}

		cleared := true
		reconciled := false

		credit, err := decimal.NewFromString(record[4])
		if err != nil {
			log.Print(err)
		}
		debit, err := decimal.NewFromString(record[3])
		if err != nil {
			log.Print(err)
		}

		trans := Transaction{
			Credit:       credit,
			Debit:        debit,
			IsCleared:    cleared,
			IsReconciled: reconciled,
			Payee:        record[2],
			Date:         transDate,
		}
		a.AddTransaction(trans)
	}
}
开发者ID:yendor,项目名称:lunchmoney,代码行数:44,代码来源:account.go

示例11: TestCurrencyDivisionByZero

func TestCurrencyDivisionByZero(t *testing.T) {
	fromUSD, err := decimal.NewFromString("0")

	if err != nil {
		t.Fatal(err)
	}

	f, _ := fromUSD.Float64()

	if f != 0 {
		oneD.Div(fromUSD)
	}
}
开发者ID:simonz05,项目名称:currency,代码行数:13,代码来源:currency_test.go

示例12: normalizeCurrencyData

func (ex *Exchange) normalizeCurrencyData(yahooData *yahooCurrencyResponse) (map[Currency]ExchangeRate, error) {
	data := make(map[Currency]ExchangeRate)

	for _, res := range yahooData.List.Resources {
		sym := res.Resource.Fields.Symbol

		// exp EUR=X
		if len(sym) != 5 {
			return nil, ErrCurrencyLength
		}

		cur, err := ParseCurrency(sym[:3])

		if err != nil {
			if err == ErrCurrencyUnknown {
				continue
			}
			return nil, err
		}

		price := res.Resource.Fields.Price

		// extra check
		f, err := strconv.ParseFloat(price, 64)

		if err != nil {
			return nil, err
		}

		isZero := f == 0
		fromUSD, err := decimal.NewFromString(price)

		if err != nil {
			return nil, err
		}

		toUSD := fromUSD

		if !isZero {
			toUSD = oneD.Div(fromUSD)
		}

		toUSD = oneD.Div(fromUSD)
		data[cur] = ExchangeRate{
			FromUSD: fromUSD,
			ToUSD:   toUSD,
		}
	}

	return data, nil
}
开发者ID:simonz05,项目名称:currency,代码行数:51,代码来源:exchange.go

示例13: NewTSPCoord

func NewTSPCoord(id string, origLat string, origLon string, mode string) (*TSPCoord, error) {
	intId, err := strconv.Atoi(id)
	if err != nil {
		return nil, err
	}
	decimalLat, err := decimal.NewFromString(origLat)
	if err != nil {
		return nil, err
	}
	decimalLon, err := decimal.NewFromString(origLon)
	if err != nil {
		return nil, err
	}
	tspCoord := &TSPCoord{Id: intId, OrigLat: origLat, OrigLon: origLon,
		Coord:      NewCoord(decimalLat, decimalLon),
		Duplicates: NewTSPCoordList(), CostTable: NewCostTable()}
	switch {
	case mode == "EUC_2D":
		tspCoord.fromEUC2D()
	}
	tspCoord.CoordHash = fmt.Sprintf("%s_%s", origLat, origLon)
	return tspCoord, nil
}
开发者ID:fernandosanchezjr,项目名称:gotsp,代码行数:23,代码来源:tspcoords.go

示例14: 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

示例15: main

func main() {

	account := bank.CreateAccount(1)
	account.Deposit(decimal.NewFromFloat(1000.50))

	reader := bufio.NewReader(os.Stdin)

	fmt.Println("Welcome to the Go ATM service!\n")

	for {

		fmt.Println("1. View current balance.")
		fmt.Println("2. Withdraw.")
		fmt.Println("3. Exit.")

		actionStr, _ := reader.ReadString('\n')
		action, _ := strconv.ParseInt(strings.TrimSpace(actionStr), 10, 32)

		switch action {
		case 1:
			fmt.Println(account.GetBalance().String())
		case 2:
			fmt.Println("\nWithdraw amount:")
			amountStr, _ := reader.ReadString('\n')
			amount, _ := decimal.NewFromString(strings.TrimSpace(amountStr))

			_, err := account.Withdraw(amount)

			if err != nil {
				fmt.Println(err)
			}

		case 3:
			os.Exit(0)
		}

	}

}
开发者ID:Hinton,项目名称:go-learn,代码行数:39,代码来源:atm.go


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