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


Golang strconv.FormatFloat函数代码示例

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


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

示例1: LoadAvg

func LoadAvg() (s []string) {

	v, err := syscall.Sysctl(sysctl)
	t := time.Now()
	etime := strconv.FormatInt(t.Unix(), 10)

	if err != nil {
		fmt.Println(err)
	}
	b := []byte(v)
	var l loadavg = *(*loadavg)(unsafe.Pointer(&b[0]))

	scale := float64(l.scale)
	c := strconv.FormatFloat(float64(l.ldavg[0])/scale, 'f', 2, 64)
	d := strconv.FormatFloat(float64(l.ldavg[1])/scale, 'f', 2, 64)
	e := strconv.FormatFloat(float64(l.ldavg[2])/scale, 'f', 2, 64)

	// returning as load.load.metric because that's what collectd does
	f := fmt.Sprintf("load.load.shortterm %s %s", c, etime)
	s = append(s, f)
	g := fmt.Sprintf("load.load.midterm %s %s", d, etime)
	s = append(s, g)
	h := fmt.Sprintf("load.load.longterm %s %s", e, etime)
	s = append(s, h)
	return s
}
开发者ID:eholzbach,项目名称:lespace,代码行数:26,代码来源:load_fbsd.go

示例2: Execute

func (h C1G2Summary) Execute(report gr.GoReport) {
	report.Font("MPBOLD", 9, "")
	y := 15.0
	report.CellRight(123, y, 20, "Total:")
	report.CellRight(150, y, 20, gr.AddComma(strconv.FormatFloat(
		report.SumWork["g2hrcum"], 'f', 1, 64))+" Hrs")
	report.CellRight(170, y, 26, gr.AddComma(strconv.FormatFloat(
		report.SumWork["g2amtcum"], 'f', 2, 64))+" USD")
	y = 25.0
	report.CellRight(123, y, 20, "Tax:")
	report.CellRight(150, y, 20, "7.75%")
	tax := report.SumWork["g2amtcum"] * 0.0775
	report.CellRight(170, y, 26, gr.AddComma(strconv.FormatFloat(
		tax, 'f', 2, 64))+" USD")
	report.LineType("straight", 0.3)
	report.LineH(170, 33, 199)
	y = 39.0
	report.Font("MPBOLD", 11, "")
	report.CellRight(123, y, 20, "AMOUT DUE:")
	report.CellRight(170, y, 26, gr.AddComma(strconv.FormatFloat(
		report.SumWork["g2amtcum"]+tax, 'f', 2, 64))+" USD")
	report.NewPage(true)
	report.SumWork["g2item"] = 0.0
	report.SumWork["g2hrcum"] = 0.0
	report.SumWork["g2amtcum"] = 0.0
}
开发者ID:Tom-Kail,项目名称:goreport,代码行数:26,代码来源:complex1.go

示例3: getGoogLocation

func getGoogLocation(address string) OutputAddress {
	client := &http.Client{}
	reqURL := "http://maps.google.com/maps/api/geocode/json?address="
	reqURL += url.QueryEscape(address)
	reqURL += "&sensor=false"
	fmt.Println("URL formed: " + reqURL)
	req, err := http.NewRequest("GET", reqURL, nil)
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("error in sending req to google: ", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("error in reading response: ", err)
	}
	var res GoogleResponse
	err = json.Unmarshal(body, &res)
	if err != nil {
		fmt.Println("error in unmashalling response: ", err)
	}

	//The func to find google's response

	var ret OutputAddress
	ret.Coordinate.Lat = strconv.FormatFloat(res.Results[0].Geometry.Location.Lat, 'f', 7, 64)
	ret.Coordinate.Lang = strconv.FormatFloat(res.Results[0].Geometry.Location.Lng, 'f', 7, 64)

	return ret
}
开发者ID:minervaDutta,项目名称:CMPE273-Assignment3,代码行数:31,代码来源:controller.go

示例4: ToString

// ToString gets the string representation of the datum.
func (d *Datum) ToString() (string, error) {
	switch d.Kind() {
	case KindInt64:
		return strconv.FormatInt(d.GetInt64(), 10), nil
	case KindUint64:
		return strconv.FormatUint(d.GetUint64(), 10), nil
	case KindFloat32:
		return strconv.FormatFloat(float64(d.GetFloat32()), 'f', -1, 32), nil
	case KindFloat64:
		return strconv.FormatFloat(float64(d.GetFloat64()), 'f', -1, 64), nil
	case KindString:
		return d.GetString(), nil
	case KindBytes:
		return d.GetString(), nil
	case KindMysqlTime:
		return d.GetMysqlTime().String(), nil
	case KindMysqlDuration:
		return d.GetMysqlDuration().String(), nil
	case KindMysqlDecimal:
		return d.GetMysqlDecimal().String(), nil
	case KindMysqlHex:
		return d.GetMysqlHex().ToString(), nil
	case KindMysqlBit:
		return d.GetMysqlBit().ToString(), nil
	case KindMysqlEnum:
		return d.GetMysqlEnum().String(), nil
	case KindMysqlSet:
		return d.GetMysqlSet().String(), nil
	default:
		return "", errors.Errorf("cannot convert %v(type %T) to string", d.GetValue(), d.GetValue())
	}
}
开发者ID:yangxuanjia,项目名称:tidb,代码行数:33,代码来源:datum.go

示例5: CoerceString

// Coerce types (string,int,int64, float, []byte) into String type
func CoerceString(v interface{}) (string, error) {
	switch val := v.(type) {
	case string:
		if val == "null" || val == "NULL" {
			return "", nil
		}
		return val, nil
	case int:
		return strconv.Itoa(val), nil
	case int32:
		return strconv.FormatInt(int64(val), 10), nil
	case int64:
		return strconv.FormatInt(val, 10), nil
	case uint32:
		return strconv.FormatUint(uint64(val), 10), nil
	case uint64:
		return strconv.FormatUint(val, 10), nil
	case float32:
		return strconv.FormatFloat(float64(val), 'f', -1, 32), nil
	case float64:
		return strconv.FormatFloat(val, 'f', -1, 64), nil
	case []byte:
		if string(val) == "null" || string(val) == "NULL" {
			return "", nil
		}
		return string(val), nil
	case json.RawMessage:
		if string(val) == "null" || string(val) == "NULL" {
			return "", nil
		}
		return string(val), nil
	}
	return "", fmt.Errorf("Could not coerce to string: %v", v)
}
开发者ID:albertzak,项目名称:transporter,代码行数:35,代码来源:coerce.go

示例6: checkResults

//checkResults checks the results between
func checkResults() string {
	for metric, expected := range expectedValues {
		switch m := metric.(type) {
		case *metrics.Counter:
			val, ok := expected.(uint64)
			if !ok {
				return "unexpected type"
			}
			if m.Get() != val {
				return ("unexpected value - got: " +
					strconv.FormatInt(int64(m.Get()), 10) + " but wanted " + strconv.FormatInt(int64(val), 10))
			}
		case *metrics.Gauge:
			val, ok := expected.(float64)
			if !ok {
				return "unexpected type"
			}
			if m.Get() != val {
				return ("unexpected value - got: " +
					strconv.FormatFloat(float64(m.Get()), 'f', 5, 64) + " but wanted " +
					strconv.FormatFloat(float64(val), 'f', 5, 64))
			}
		}
	}
	return ""
}
开发者ID:njuettner,项目名称:inspect,代码行数:27,代码来源:dbstat_test.go

示例7: SendLocation

// SendLocation sends a location to a chat.
//
// Requires ChatID, Latitude, and Longitude.
// ReplyToMessageID and ReplyMarkup are optional.
func (bot *BotAPI) SendLocation(config LocationConfig) (Message, error) {
	v := url.Values{}
	v.Add("chat_id", strconv.Itoa(config.ChatID))
	v.Add("latitude", strconv.FormatFloat(config.Latitude, 'f', 6, 64))
	v.Add("longitude", strconv.FormatFloat(config.Longitude, 'f', 6, 64))
	if config.ReplyToMessageID != 0 {
		v.Add("reply_to_message_id", strconv.Itoa(config.ReplyToMessageID))
	}
	if config.ReplyMarkup != nil {
		data, err := json.Marshal(config.ReplyMarkup)
		if err != nil {
			return Message{}, err
		}

		v.Add("reply_markup", string(data))
	}

	resp, err := bot.MakeRequest("sendLocation", v)
	if err != nil {
		return Message{}, err
	}

	var message Message
	json.Unmarshal(resp.Result, &message)

	if bot.Debug {
		log.Printf("sendLocation req : %+v\n", v)
		log.Printf("sendLocation resp: %+v\n", message)
	}

	return message, nil
}
开发者ID:gobwas,项目名称:telegram-bot-api,代码行数:36,代码来源:methods.go

示例8: StreamRun

func StreamRun(model_file string, instances []string) (string, error) {
	log := util.GetLogger()
	if !util.FileExists(model_file) || len(instances) == 0 {
		log.Error("[Predictor-StreamRun] Model file or instances error.")
		return fmt.Sprintf(errorjson, "[Predictor-StreamRun] Model file or instances error."), errors.New("[Predictor-StreamRun] Model file or instances error.")
	}

	var rtstr string
	var model solver.LRModel
	model.Initialize(model_file)
	for i := 0; i < len(instances); i++ {
		res, _, x := util.ParseSample(instances[i])
		if res != nil {
			break
		}

		pred := model.Predict(x)
		pred = math.Max(math.Min(pred, 1.-10e-15), 10e-15)
		if i == len(instances)-1 {
			rtstr += strconv.FormatFloat(pred, 'f', 6, 64)
		} else {
			rtstr += strconv.FormatFloat(pred, 'f', 6, 64) + ","
		}
	}

	return fmt.Sprintf(streamjson, rtstr), nil
}
开发者ID:vivounicorn,项目名称:goline,代码行数:27,代码来源:ftrl_predict.go

示例9: ToString

func ToString(a interface{}) string {

	if v, p := a.(int); p {
		return strconv.Itoa(v)
	}

	if v, p := a.(float64); p {
		return strconv.FormatFloat(v, 'f', -1, 64)
	}

	if v, p := a.(float32); p {
		return strconv.FormatFloat(float64(v), 'f', -1, 32)
	}

	if v, p := a.(int16); p {
		return strconv.Itoa(int(v))
	}
	if v, p := a.(uint); p {
		return strconv.Itoa(int(v))
	}
	if v, p := a.(int32); p {
		return strconv.Itoa(int(v))
	}
	return "wrong"
}
开发者ID:ezhong0812,项目名称:Lighter3,代码行数:25,代码来源:TSUtil.go

示例10: appInfoHandler

func appInfoHandler(w rest.ResponseWriter, r *rest.Request) {
	var marathonApps marathon.MarathonAppsGlobalInfoResponse
	fasthttp.JsonReqAndResHandler(goCore.MarathonAppsUrl, nil, &marathonApps, "GET")
	appsCnt := len(marathonApps.Apps)

	// should not code like this: appsGlobalInfos := [appsCnt]entity.AppsGlobalInfo{}
	appsGlobalInfos := make([]dto.AppsGlobalInfoResponse, appsCnt)

	for i, v := range marathonApps.Apps {
		var perApp dto.AppsGlobalInfoResponse
		if strings.LastIndex(v.Id, "/") == -1 {
			perApp.Id = v.Id
		} else {
			perApp.Id = v.Id[strings.LastIndex(v.Id, "/")+1:]
		}
		perApp.Cpus = strconv.FormatFloat(v.Cpus, 'f', 1, 64)
		perApp.CurrentInstances = strconv.Itoa(v.TasksRunning)
		fmt.Println(v)
		if strings.LastIndex(v.Id, "/") <= 0 { // exclude like /zk or zk
			perApp.Group = "No Groups"
		} else {
			perApp.Group = v.Id[0:strings.LastIndex(v.Id, "/")]
		}
		perApp.Instances = strconv.Itoa(v.Instances)
		perApp.Mem = strconv.FormatFloat(v.Mem, 'f', 1, 64)
		if v.TasksHealthy == 0 && v.TasksUnhealthy == 0 { // when no and healthy check
			perApp.Healthy = "100"
		} else {
			perApp.Healthy = strconv.FormatFloat(float64(v.TasksHealthy)/float64(v.TasksHealthy+v.TasksUnhealthy), 'f', 1, 64)
		}
		perApp.FormatStatus(v.TasksStaged)
		appsGlobalInfos[i] = perApp
	}
	w.WriteJson(appsGlobalInfos)
}
开发者ID:konce,项目名称:chaos,代码行数:35,代码来源:bootstrap.go

示例11: encodeBasic

func encodeBasic(v reflect.Value) string {
	t := v.Type()
	switch k := t.Kind(); k {
	case reflect.Bool:
		return strconv.FormatBool(v.Bool())
	case reflect.Int,
		reflect.Int8,
		reflect.Int16,
		reflect.Int32,
		reflect.Int64:
		return strconv.FormatInt(v.Int(), 10)
	case reflect.Uint,
		reflect.Uint8,
		reflect.Uint16,
		reflect.Uint32,
		reflect.Uint64:
		return strconv.FormatUint(v.Uint(), 10)
	case reflect.Float32:
		return strconv.FormatFloat(v.Float(), 'g', -1, 32)
	case reflect.Float64:
		return strconv.FormatFloat(v.Float(), 'g', -1, 64)
	case reflect.Complex64, reflect.Complex128:
		s := fmt.Sprintf("%g", v.Complex())
		return strings.TrimSuffix(strings.TrimPrefix(s, "("), ")")
	case reflect.String:
		return v.String()
	}
	panic(t.String() + " has unsupported kind " + t.Kind().String())
}
开发者ID:henryren,项目名称:form,代码行数:29,代码来源:encode.go

示例12: SetValue

func (b *Balance) SetValue(amount float64) {
	b.Value = amount
	b.Value = utils.Round(b.GetValue(), globalRoundingDecimals, utils.ROUNDING_MIDDLE)
	b.dirty = true

	// publish event
	accountId := ""
	allowNegative := ""
	disabled := ""
	if b.account != nil {
		accountId = b.account.Id
		allowNegative = strconv.FormatBool(b.account.AllowNegative)
		disabled = strconv.FormatBool(b.account.Disabled)
	}
	Publish(CgrEvent{
		"EventName":            utils.EVT_ACCOUNT_BALANCE_MODIFIED,
		"Uuid":                 b.Uuid,
		"Id":                   b.Id,
		"Value":                strconv.FormatFloat(b.Value, 'f', -1, 64),
		"ExpirationDate":       b.ExpirationDate.String(),
		"Weight":               strconv.FormatFloat(b.Weight, 'f', -1, 64),
		"DestinationIds":       b.DestinationIds,
		"RatingSubject":        b.RatingSubject,
		"Category":             b.Category,
		"SharedGroup":          b.SharedGroup,
		"TimingIDs":            b.TimingIDs,
		"Account":              accountId,
		"AccountAllowNegative": allowNegative,
		"AccountDisabled":      disabled,
	})
}
开发者ID:nikbyte,项目名称:cgrates,代码行数:31,代码来源:balances.go

示例13: Validate

func (m *floatValueValidation) Validate(value interface{}, obj reflect.Value) *ValidationError {
	var compareValue float64
	switch value := value.(type) {
	case float32:
		compareValue = float64(value)
	case float64:
		compareValue = float64(value)
	default:
		return &ValidationError{
			Key:     m.FieldName(),
			Message: "is not convertible to type float64",
		}
	}

	if m.less {
		if compareValue < m.value {
			return &ValidationError{
				Key:     m.FieldName(),
				Message: "must be greater than or equal to " + strconv.FormatFloat(m.value, 'E', -1, 64),
			}
		}
	} else {
		if compareValue > m.value {
			return &ValidationError{
				Key:     m.FieldName(),
				Message: "must be less than or equal to " + strconv.FormatFloat(m.value, 'E', -1, 64),
			}
		}
	}

	return nil
}
开发者ID:BakedSoftware,项目名称:go-validation,代码行数:32,代码来源:numeric.go

示例14: GetTimers

func GetTimers(request *Request) []string {
	offset := 0
	timers := make([]string, len(request.TimerValue))
	for idx, val := range request.TimerValue {
		var timer bytes.Buffer
		var cputime float64 = 0.0
		if len(request.TimerUtime) == len(request.TimerValue) {
			cputime = float64(request.TimerUtime[idx] + request.TimerStime[idx])
		}

		timer.WriteString("Val: ")
		timer.WriteString(strconv.FormatFloat(float64(val), 'f', 4, 64))
		timer.WriteString(" Hit: ")
		timer.WriteString(strconv.FormatInt(int64(request.TimerHitCount[idx]), 10))
		timer.WriteString(" CPU: ")
		timer.WriteString(strconv.FormatFloat(cputime, 'f', 4, 64))
		timer.WriteString(" Tags: ")

		for k, key_idx := range request.TimerTagName[offset : offset+int(request.TimerTagCount[idx])] {
			val_idx := request.TimerTagValue[int(offset)+k]
			if val_idx >= uint32(len(request.Dictionary)) || key_idx >= uint32(len(request.Dictionary)) {
				continue
			}
			timer.WriteString(" ")
			timer.WriteString(request.Dictionary[key_idx])
			timer.WriteString("=")
			timer.WriteString(request.Dictionary[val_idx])
		}

		timers[idx] = timer.String()
		offset += int(request.TimerTagCount[idx])
	}
	return timers
}
开发者ID:AlexeyKupershtokh,项目名称:pinba-server,代码行数:34,代码来源:main.go

示例15: computeProbability

func (this *Probability) computeProbability(tag string, prob float64, s string) float64 {
	x := prob
	spos := len(s)
	found := true
	var pt float64
	TRACE(4, " suffixes. Tag "+tag+" initial prob="+strconv.FormatFloat(prob, 'f', -1, 64), MOD_PROBABILITY)
	for spos > 0 && found {
		spos--
		is := this.unkSuffS[s[spos:]]
		found = is != nil
		if found {
			pt = is[tag]
			if pt != 0 {
				TRACE(4, "    found prob for suffix -"+s[spos:], MOD_PROBABILITY)
			} else {
				pt = 0
				TRACE(4, "    NO prob found for suffix -"+s[spos:], MOD_PROBABILITY)
			}

			x = (pt + this.theeta*x) / (1 + this.theeta)
		}
	}

	TRACE(4, "      final prob="+strconv.FormatFloat(x, 'f', -1, 64), MOD_PROBABILITY)
	return x
}
开发者ID:payfriendz,项目名称:go-freeling,代码行数:26,代码来源:probability.go


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