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

Nag*_*sha 3 string floating-point precision go

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

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?
Run Code Online (Sandbox Code Playgroud)

ASH*_*EEV 13

将浮点数转换为字符串

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) 
Run Code Online (Sandbox Code Playgroud)

输出为“3.14159265”

另一种方法是使用fmt.Sprintf

s := fmt.Sprintf("%f", 123.456) 
fmt.Println(s)
Run Code Online (Sandbox Code Playgroud)

输出为“123.456000”

检查游乐场上的代码

  • 事实上,“FormatFloat”更快并且分配更少。 (2认同)

Ull*_*kut 6

像这样使用strconv.FormatFloat

s := strconv.FormatFloat(3.1415, 'E', -1, 64)
fmt.Println(s)
Run Code Online (Sandbox Code Playgroud)

输出

3.1415


小智 6

func main() {
    var x float32
    var y string
    x= 10.5
    y = fmt.Sprint(x)
    fmt.Println(y)
}
Run Code Online (Sandbox Code Playgroud)