当前位置: 首页>>代码示例>>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;未经允许,请勿转载。