duanpao4522
2018-01-19 08:58
浏览 1.7k
已采纳

如何在Golang中将浮点数打印为字符串而不用科学记数法

Suppose I have an array with 2 items whose type is string / float. How should I print them together without scientific notation for float item.

For example:

package main

import (
    "fmt"
)

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

The output will be

mydata

1.234567890123e+09

What I want is

mydata

1234567890.123

图片转代码服务由CSDN问答提供 功能建议

假设我有一个数组,其中包含2个类型为string / float的项目。 如何在不科学的情况下将它们一起打印 浮点符号。

例如:

 包main 
 
import(
“ fmt” 
)
  
func main(){
值:= []界面{} {“ mydata”,1234567890.123} 
表示_,v:=范围值{
 fmt.Printf(“%v 
”,v)\  n} 
} 
   
 
 

输出将是

mydata \ n

1.234567890123e + 09

我想要的是

mydata

1234567890.123

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • du131642 2018-01-19 09:05
    最佳回答

    The package doc of fmt explains it: The %v verb is the default format, which for floating numbers means / reverts to %g which is

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

    If you always want "decimal point but no exponent, e.g. 123.456", use %f explicitly.

    But you can only use that for floating numbers, so you have to check the type of the value you print. For that you may use a type switch or type assertion.

    Example:

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

    Output (try it on the Go Playground):

    mydata
    1234567890.123000
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题