gpt4 book ai didi

go - 如何在没有科学记数法的情况下在 Golang 中将 float 打印为字符串

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

假设我有一个包含 2 个项目的数组,其类型为字符串/ float 。对于 float 项目,如果没有科学计数法,我应该如何将它们打印在一起。

例如:

package main

import (
"fmt"
)

func main() {
values := []interface{}{"mydata", 1234567890.123}
for _, v := range values{
fmt.Printf("%v\n", v)
}
}

输出将是

mydata

1.234567890123e+09

我想要的是

mydata

1234567890.123

最佳答案

fmt 的包文档对此进行了解释:%v 动词是默认格式,对于 float 意味着/恢复为 %g

%e for large exponents, %f otherwise. Precision is discussed below.

如果您总是想要“小数点但没有指数,例如 123.456”,请明确使用 %f

但是你只能将它用于 float ,所以你必须检查你打印的值的类型。为此,您可以使用 type switchtype assertion

例子:

switch v.(type) {
case float64, float32:
fmt.Printf("%f\n", v)
default:
fmt.Printf("%v\n", v)
}

输出(在 Go Playground 上尝试):

mydata
1234567890.123000

关于go - 如何在没有科学记数法的情况下在 Golang 中将 float 打印为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48337330/

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