當前位置: 首頁>>代碼示例>>Golang>>正文


Golang strconv.ParseFloat函數代碼示例

本文整理匯總了Golang中strconv.ParseFloat函數的典型用法代碼示例。如果您正苦於以下問題:Golang ParseFloat函數的具體用法?Golang ParseFloat怎麽用?Golang ParseFloat使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了ParseFloat函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: checkAccount

func (w *Huobi) checkAccount(a, price, amount string) bool {
	btc, cny := w.get_account_info()

	FPrice, err := strconv.ParseFloat(price, 64)
	if err != nil {
		logger.Debugln("price is not float")
		return false
	}
	FAmount, err := strconv.ParseFloat(amount, 64)
	if err != nil {
		logger.Debugln("amount is not float")
		return false
	}
	if a == "do_buy" {
		if float64(cny) < FPrice*FAmount {
			return false
		}
	} else {
		if float64(btc) < FAmount {
			return false
		}
	}

	return true
}
開發者ID:kuainiao,項目名稱:btcrobot,代碼行數:25,代碼來源:huobiapi.go

示例2: onRequest

func onRequest(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	f := &Frame{xrange, yrange}
	{
		v, err := strconv.ParseFloat(req.FormValue("xr"), 64)
		if err == nil {
			f.xrange = v
		}
		v, err = strconv.ParseFloat(req.FormValue("yr"), 64)
		if err == nil {
			f.yrange = v
		}
	}
	i := &Image{width, height}
	{
		v, err := strconv.Atoi(req.FormValue("w"))
		if err == nil {
			i.width = v
		}
		v, err = strconv.Atoi(req.FormValue("h"))
		if err == nil {
			i.height = v
		}
	}
	run(w, f, i)
}
開發者ID:skhal,項目名稱:gopl_old,代碼行數:26,代碼來源:mandelbrot.go

示例3: doRow0

func doRow0(top *Top, line string) {

	rexp := regexp.MustCompile(`top[\s\-0-9:]+up([:0-9A-z,\s]+?)([0-9] user.*)`)
	matches := rexp.FindStringSubmatch(line)
	if len(matches) != 3 {
		return
	}

	top.Uptime = strings.Trim(matches[1], " ,")

	ls := strings.Split(matches[2], ",")
	if len(ls) != 4 {
		return
	}
	// users
	ls[0] = strings.TrimSpace(ls[0])
	top.Users, _ = strconv.Atoi(strings.Split(ls[0], " ")[0])
	// load avgs
	// 5
	if i := strings.Index(ls[1], "load average:"); i > -1 {
		ls[1] = strings.TrimSpace(ls[1][i+13:])
		top.LoadAvg5, _ = strconv.ParseFloat(ls[1], 64)
	}
	// 10
	top.LoadAvg10, _ = strconv.ParseFloat(strings.TrimSpace(ls[2]), 64)
	// 15
	top.LoadAvg15, _ = strconv.ParseFloat(strings.TrimSpace(ls[3]), 64)
}
開發者ID:gabstv,項目名稱:go-topcmdparser,代碼行數:28,代碼來源:topcmdparser.go

示例4: Get

func (pfs *ProcFS) Get(k string) {
	var uf = path.Join(procfsdir, "uptime")
	switch k {
	case PROCFS_SELF:
		var selfdir = path.Join(procfsdir, "self")
		if !exists(selfdir) {
			return
		}
		fi, _ := os.Readlink(selfdir)
		pfs.Self = fi
	case PROCFS_UPTIME:
		str, err := ioutil.ReadFile(uf)
		if err == nil {
			ss := strings.Fields(string(str))
			if len(ss) >= 2 {
				it, _ := strconv.ParseFloat(ss[0], 64)
				pfs.Uptime = int(it)
			}
		}
	case PROCFS_IDLETIME:
		str, err := ioutil.ReadFile(uf)
		if err == nil {
			ss := strings.Fields(string(str))
			if len(ss) >= 2 {
				it, _ := strconv.ParseFloat(ss[1], 64)
				pfs.Idletime = int(it)
			}
		}
	case PROCFS_MOUNTS:
		pfs.Mounts = getMounts(path.Join(procfsdir, "mounts"))
	}
}
開發者ID:bytbox,項目名稱:procfs.go,代碼行數:32,代碼來源:procfs.go

示例5: transform

func transform(extractChannel, transformChannel chan *Order) {
	f, _ := os.Open("./../productList.txt")
	defer f.Close()
	r := csv.NewReader(f)

	records, _ := r.ReadAll()

	productList := make(map[string]*Product)

	for _, record := range records {
		product := new(Product)
		product.PartNumber = record[0]
		product.UnitCost, _ = strconv.ParseFloat(record[1], 64)
		product.UnitPrice, _ = strconv.ParseFloat(record[2], 64)
		productList[product.PartNumber] = product
	}

	for o := range extractChannel {
		time.Sleep(3 * time.Millisecond)
		o.UnitCost = productList[o.PartNumber].UnitCost
		o.UnitPrice = productList[o.PartNumber].UnitPrice
		transformChannel <- o
	}

	close(transformChannel)

}
開發者ID:rudijs,項目名稱:golang-etl,代碼行數:27,代碼來源:main.go

示例6: CoerceFloat

func CoerceFloat(v interface{}) (float64, error) {
	switch val := v.(type) {
	case int:
		return float64(val), nil
	case int32:
		return float64(val), nil
	case int64:
		return float64(val), nil
	case uint32:
		return float64(val), nil
	case uint64:
		return float64(val), nil
	case float64:
		return val, nil
	case string:
		if len(val) > 0 {
			if iv, err := strconv.ParseFloat(val, 64); err == nil {
				return iv, nil
			}
		}
	case []byte:
		if len(val) > 0 {
			if iv, err := strconv.ParseFloat(string(val), 64); err == nil {
				return iv, nil
			}
		}
	case json.RawMessage:
		if len(val) > 0 {
			if iv, err := strconv.ParseFloat(string(val), 64); err == nil {
				return iv, nil
			}
		}
	}
	return 0, fmt.Errorf("Could not Coerce Value: %v", v)
}
開發者ID:albertzak,項目名稱:transporter,代碼行數:35,代碼來源:coerce.go

示例7: splitBoundariesFloatColumn

func (qs *QuerySplitter) splitBoundariesFloatColumn(pkMinMax *sqltypes.Result) ([]sqltypes.Value, error) {
	boundaries := []sqltypes.Value{}
	if pkMinMax == nil || len(pkMinMax.Rows) != 1 || pkMinMax.Rows[0][0].IsNull() || pkMinMax.Rows[0][1].IsNull() {
		return boundaries, nil
	}
	min, err := strconv.ParseFloat(pkMinMax.Rows[0][0].String(), 64)
	if err != nil {
		return nil, err
	}
	max, err := strconv.ParseFloat(pkMinMax.Rows[0][1].String(), 64)
	if err != nil {
		return nil, err
	}
	interval := (max - min) / float64(qs.splitCount)
	if interval == 0 {
		return nil, err
	}
	qs.rowCount = int64(interval)
	for i := 1; i < int(qs.splitCount); i++ {
		boundary := min + interval*float64(i)
		v, err := sqltypes.BuildValue(boundary)
		if err != nil {
			return nil, err
		}
		boundaries = append(boundaries, v)
	}
	return boundaries, nil
}
開發者ID:littleyang,項目名稱:vitess,代碼行數:28,代碼來源:query_splitter.go

示例8: main

func main() {
	csvfile, err := os.Open("rosalind_ini2.txt")
	if err != nil {
		log.Fatal(err)
	}

	defer csvfile.Close()

	reader := csv.NewReader(csvfile)
	reader.Comma = ' '
	reader.FieldsPerRecord = 2

	records, err := reader.ReadAll()
	if err != nil {
		log.Fatal(err)
	}

	for _, record := range records {
		a, err := strconv.ParseFloat(record[0], 64)
		if err != nil {
			log.Fatal(err)
		}

		b, err := strconv.ParseFloat(record[1], 64)
		if err != nil {
			log.Fatal(err)
		}

		result := (a * a) + (b * b)
		fmt.Printf("%f\n", result)
		return
	}
}
開發者ID:serverhorror,項目名稱:rosalind-exercises,代碼行數:33,代碼來源:ini2.go

示例9: getLocationInfoNUS

// Get location (name, lat and lng)
// via NUS Web
func getLocationInfoNUS(query string) ([]LocationInfo, error) {
	url := fmt.Sprintf("http://map.nus.edu.sg/index.php/search/by/%s", query)
	doc, err := goquery.NewDocument(url)
	if err != nil {
		return nil, err
	}

	var locations []LocationInfo

	s := doc.Find("#search_list a[href=\"javascript:void(0)\"]").First()

	onclick, _ := s.Attr("onclick")
	regex := regexp.MustCompile("long=([0-9\\.]+?)&lat=([0-9\\.]+?)'")
	matches := regex.FindAllStringSubmatch(onclick, -1)

	if len(matches) == 0 || len(matches[0]) != 3 {
		return nil, fmt.Errorf("Can't find lat and lng from query: %s", query)
	}

	x, _ := strconv.ParseFloat(matches[0][1], 64)
	y, _ := strconv.ParseFloat(matches[0][2], 64)

	location := LocationInfo{
		Name: s.Text(),
		Lng:  x,
		Lat:  y,
	}

	locations = append(locations, location)

	return locations, nil
}
開發者ID:ruqqq,項目名稱:nuswherebot,代碼行數:34,代碼來源:main.go

示例10: UnmarshalJSON

// UnmarshalJSON implements json.Unmarshaller on AccountInfo.
// This is needed because the Vultr API is inconsistent in it's JSON responses for account info.
// Some fields can change type, from JSON number to JSON string and vice-versa.
func (a *AccountInfo) UnmarshalJSON(data []byte) (err error) {
	if a == nil {
		*a = AccountInfo{}
	}

	var fields map[string]interface{}
	if err := json.Unmarshal(data, &fields); err != nil {
		return err
	}

	b, err := strconv.ParseFloat(fmt.Sprintf("%v", fields["balance"]), 64)
	if err != nil {
		return err
	}
	a.Balance = b

	pc, err := strconv.ParseFloat(fmt.Sprintf("%v", fields["pending_charges"]), 64)
	if err != nil {
		return err
	}
	a.PendingCharges = pc

	lpa, err := strconv.ParseFloat(fmt.Sprintf("%v", fields["last_payment_amount"]), 64)
	if err != nil {
		return err
	}
	a.LastPaymentAmount = lpa

	a.LastPaymentDate = fmt.Sprintf("%v", fields["last_payment_date"])

	return
}
開發者ID:janeczku,項目名稱:rancher-letsencrypt,代碼行數:35,代碼來源:account_info.go

示例11: Monitor

func (sm *statMonitor) Monitor(packets <-chan StatPacket, wg *sync.WaitGroup) {
	var s StatPacket
	var floatValue float64
	var intValue int

	t := time.Tick(time.Duration(sm.flushInterval) * time.Second)
	ok := true
	for ok {
		select {
		case <-t:
			sm.Flush()
		case s, ok = <-packets:
			if !ok {
				sm.Flush()
				break
			}
			switch s.Modifier {
			case "ms":
				floatValue, _ = strconv.ParseFloat(s.Value, 64)
				sm.timers[s.Bucket] = append(sm.timers[s.Bucket], floatValue)
			case "g":
				intValue, _ = strconv.Atoi(s.Value)
				sm.gauges[s.Bucket] += intValue
			default:
				floatValue, _ = strconv.ParseFloat(s.Value, 32)
				sm.counters[s.Bucket] += int(float32(floatValue) * (1 / s.Sampling))
			}
		}
	}
	log.Println("StatsdMonitor for input stopped: ", sm.ir.Name())
	wg.Done()
}
開發者ID:hellcoderz,項目名稱:heka,代碼行數:32,代碼來源:statsd_input_writer.go

示例12: handleMessage

func (s *StatsdInput) handleMessage(message []byte) {
	var packet StatPacket
	var value string
	st := sanitizeRegexp.ReplaceAllString(string(message), "")
	for _, item := range packetRegexp.FindAllStringSubmatch(st, -1) {
		value = item[2]
		if item[3] == "ms" {
			_, err := strconv.ParseFloat(item[2], 32)
			if err != nil {
				value = "0"
			}
		}

		sampleRate, err := strconv.ParseFloat(item[5], 32)
		if err != nil {
			sampleRate = 1
		}

		packet.Bucket = item[1]
		packet.Value = value
		packet.Modifier = item[3]
		packet.Sampling = float32(sampleRate)
		s.Packet <- packet
	}
}
開發者ID:hellcoderz,項目名稱:heka,代碼行數:25,代碼來源:statsd_input_writer.go

示例13: convertFloat

// convertFloat converts the string to a float64value.
func (s *ss) convertFloat(str string, n int) float64 {
	if p := indexRune(str, 'p'); p >= 0 {
		// Atof doesn't handle power-of-2 exponents,
		// but they're easy to evaluate.
		f, err := strconv.ParseFloat(str[:p], n)
		if err != nil {
			// Put full string into error.
			if e, ok := err.(*strconv.NumError); ok {
				e.Num = str
			}
			s.error(err)
		}
		m, err := strconv.Atoi(str[p+1:])
		if err != nil {
			// Put full string into error.
			if e, ok := err.(*strconv.NumError); ok {
				e.Num = str
			}
			s.error(err)
		}
		return math.Ldexp(f, m)
	}
	f, err := strconv.ParseFloat(str, n)
	if err != nil {
		s.error(err)
	}
	return f
}
開發者ID:vsayer,項目名稱:go,代碼行數:29,代碼來源:scan.go

示例14: LoadAvg

func LoadAvg() (*LoadAvgStat, error) {
	filename := common.HostProc("loadavg")
	line, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	values := strings.Fields(string(line))

	load1, err := strconv.ParseFloat(values[0], 64)
	if err != nil {
		return nil, err
	}
	load5, err := strconv.ParseFloat(values[1], 64)
	if err != nil {
		return nil, err
	}
	load15, err := strconv.ParseFloat(values[2], 64)
	if err != nil {
		return nil, err
	}

	ret := &LoadAvgStat{
		Load1:  load1,
		Load5:  load5,
		Load15: load15,
	}

	return ret, nil
}
開發者ID:sekimura,項目名稱:gopsutil,代碼行數:30,代碼來源:load_linux.go

示例15: HomeHandler

func HomeHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	vars := mux.Vars(r)
	lat, latErr := strconv.ParseFloat(vars["lat"], 32)
	if latErr != nil {
		ReturnErrorToClient(w, latErr, "Invalid latitude value. Expecting a floating point number")
		return
	}

	lng, lngErr := strconv.ParseFloat(vars["lng"], 32)
	if lngErr != nil {
		ReturnErrorToClient(w, lngErr, "Invalid longitude value. Expecting a floating point number")
		return
	}

	tracelog.Trace("Lat Value", "main", "Lat is %f", lat)
	tracelog.Trace("Lng Value", "main", "Lng is %f", lng)

	postalCode, postaCodeErr := ReverseGeocodeToPostalCode(lat, lng)
	if postaCodeErr != nil {
		ReturnErrorToClient(w, postaCodeErr, "Error determining zip code from given coordinates")
		return
	}

	tracelog.Trace("Postal Code Value", "main", "Postal Code is %s", postalCode)
	var response = GeocodeResponse{postalCode}

	w.WriteHeader(http.StatusOK)
	var err error
	if err = json.NewEncoder(w).Encode(response); err != nil {
		tracelog.Error(err, "An error occurred while encoding json response", "NearbyHandler")
		panic(err)
	}
}
開發者ID:agilemobiledev,項目名稱:pcf-vehicle-simulator-microservices,代碼行數:35,代碼來源:main.go


注:本文中的strconv.ParseFloat函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。