如何将浮点数转换为字符串

问题描述 投票:0回答:4

我从文件中读取了一个浮点数,并且必须将其转换为字符串。我的问题是我不确定小数点后有多少位。我需要准确地获取浮点数并将其转换为字符串。

For ex: 
1.10 should be converted to "1.10"
Also,
1.5 should be converted to "1.5"
Can someone suggest how to go about this?
string go floating-point precision
4个回答
20
投票

像这样使用strconv.FormatFloat

s := strconv.FormatFloat(3.1415, 'f', -1, 64)
fmt.Println(s)

输出

3.1415


11
投票

将浮点数转换为字符串

FormatFloat 根据格式 fmt 和精度 prec 将浮点数 f 转换为字符串。它假设原始结果是从 bitSize 位的浮点值(对于 float32 为 32,对于 float64 为 64)获得的结果进行四舍五入。

func FormatFloat(f float64, fmt byte, prec, bitSize int) 字符串

f := 3.14159265
s := strconv.FormatFloat(f, 'E', -1, 64)
fmt.Println(s) 

输出为“3.14159265”

另一种方法是使用

fmt.Sprintf

s := fmt.Sprintf("%f", 123.456) 
fmt.Println(s)

输出为“123.456000”

检查游乐场

的代码

7
投票
func main() {
    var x float32
    var y string
    x= 10.5
    y = fmt.Sprint(x)
    fmt.Println(y)
}

1
投票

根据浮点数的大小选择最合适的选项:

var (
    floatNumber float64 = 27.156633168032640
)

fmt.Println("as float32 with 'E' (decimal exponent) :", strconv.FormatFloat(floatNumber, 'E', -1, 32))
fmt.Println("as float64 with 'E' (decimal exponent) :", strconv.FormatFloat(floatNumber, 'E', -1, 64))
fmt.Println("as float32 with 'f' (no exponent) :", strconv.FormatFloat(floatNumber, 'f', -1, 32))
fmt.Println("as float64 with 'f' (no exponent) :", strconv.FormatFloat(floatNumber, 'f', -1, 64))
fmt.Println("with fmt.Sprint :", fmt.Sprint(floatNumber))
fmt.Println("with fmt.Sprintf :", fmt.Sprintf("%f", floatNumber))

结果是:

附注为了获得更好的性能,您应该使用

strconv.FormatFloat()

© www.soinside.com 2019 - 2024. All rights reserved.