简体   繁体   English

去fmt float64问题

[英]Go fmt float64 issue

I've come across a bit of a gotcha in my noob understanding of go fmt package 我对go fmt包的理解中遇到了一些问题

It relates to the following code: 它涉及以下代码:

import "fmt" 导入“fmt”

func main() {
    var smallFloat float64 = 0.123456789
    var bigFloat float64 = 123456789000

    fmt.Println(fmt.Sprintf("%f", smallFloat))
    fmt.Println(fmt.Sprintf("%f", bigFloat))
}

The output is: 输出是:

0.123457
123456789000.000000

I don't want to use scientific notation so thought %f would suit my needs.I can see from the formatting page ( https://golang.org/pkg/fmt/ ) it says: 我不想使用科学记数法,所以认为%f符合我的需要。我可以从格式化页面( https://golang.org/pkg/fmt/ )看到它说:

The default precision for %e and %f is 6; for %g it is the smallest number of digits necessary to identify the value uniquely.

Is there a way I can use the fmt package that would allow me represent the full decimal value of smallFloat while at the same time not appending 6 zeros to the end of bigFloat? 有没有办法可以使用fmt包,它允许我代表smallFloat的完整十进制值,同时不会在bigFloat的末尾附加6个零?

You can use strconv.FormatFloat with prec set to -1: 您可以使用strconv.FormatFloat并将prec设置为-1:

fmt.Println(strconv.FormatFloat(big, 'f', -1, 64))
fmt.Println(strconv.FormatFloat(small, 'f', -1, 64))

prints 版画

123456789000
0.123456789

Playground: http://play.golang.org/p/7p8xnQ_BzE . 游乐场: http//play.golang.org/p/7p8xnQ_BzE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM