gpt4 book ai didi

string - 按照要求的格式在 go lang 中将 float 转换为 string 。

转载 作者:IT王子 更新时间:2023-10-29 00:45:14 25 4
gpt4 key购买 nike

我在 go 中有 4 个浮点值(startLat、startLon、endLat、endLon)。我想将这些值附加(替换)到以下字符串:

var etaString = []byte(`{"start_latitude":"` + startLat + `","start_longitude":"` + startLon + `","end_latitude":"` + endLat + `","end_longitude":"` + endLon }`)

在这样做之前,我必须将它们转换为字符串。

startLat := strconv.FormatFloat(o.Coordinate.Longitude, 'g', 1, 64)

但是,当我这样做时,我得到的这些参数的值为 "4e+01 -1e+02 4e+01 -1e+02"但我只想要这样的东西:“64.2345”。

我怎样才能做到这一点?TIA :)

最佳答案

Package strconv

import "strconv" > func FormatFloat

func FormatFloat(f float64, fmt byte, prec, bitSize int) string

FormatFloat converts the floating-point number f to a string, according to the format fmt and precision prec. It rounds the result assuming that the original was obtained from a floating-point value of bitSize bits (32 for float32, 64 for float64).

The format fmt is one of 'b' (-ddddp±ddd, a binary exponent), 'e' (-d.dddde±dd, a decimal exponent), 'E' (-d.ddddE±dd, a decimal exponent), 'f' (-ddd.dddd, no exponent), 'g' ('e' for large exponents, 'f' otherwise), or 'G' ('E' for large exponents, 'f' otherwise).

The precision prec controls the number of digits (excluding the exponent) printed by the 'e', 'E', 'f', 'g', and 'G' formats. For 'e', 'E', and 'f' it is the number of digits after the decimal point. For 'g' and 'G' it is the total number of digits. The special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly.

使用精度 -1,而不是 1。使用 f 格式,而不是 g 以避免大指数的指数形式(参见 HectorJ's 评论)。

startLat := strconv.FormatFloat(o.Coordinate.Longitude, 'f', -1, 64)

例如,

package main

import (
"fmt"
"strconv"
)

func main() {
f := 64.2345
s := strconv.FormatFloat(f, 'g', 1, 64)
fmt.Println(s)
s = strconv.FormatFloat(f, 'f', -1, 64)
fmt.Println(s)
}

输出:

6e+01
64.2345

关于string - 按照要求的格式在 go lang 中将 float 转换为 string 。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33852140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com