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

如何在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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • du131642
    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
    
    点赞 评论
  • dtvp3625
    dtvp3625 2018-01-19 09:03

    You can use %f to print a float. Given your slice of interfaces, you first need to check the type of the element. You can do so as follows:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        values := []interface{}{"mydata", 1234567890.123}
        for _, v := range values {
            // Check if the type conversion to float64 succeeds.
            if f, ok := v.(float64); ok {
                fmt.Printf("%f
    ", f)
            } else {
                fmt.Println(v)
            }
        }
    }
    

    Outputs:

    mydata
    1234567890.123000
    

    The full list of flags for floats from fmt is:

    %b  decimalless scientific notation with exponent a power of two,
        in the manner of strconv.FormatFloat with the 'b' format,
        e.g. -123456p-78
    %e  scientific notation, e.g. -1.234456e+78
    %E  scientific notation, e.g. -1.234456E+78
    %f  decimal point but no exponent, e.g. 123.456
    %F  synonym for %f
    %g  %e for large exponents, %f otherwise. Precision is discussed below.
    %G  %E for large exponents, %F otherwise
    
    点赞 评论

相关推荐