简体   繁体   中英

Go fmt float64 issue

I've come across a bit of a gotcha in my noob understanding of go fmt package

It relates to the following code:

import "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:

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?

You can use strconv.FormatFloat with prec set to -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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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