Reputation: 594
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?
Upvotes: 4
Views: 9515
Reputation: 36199
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.
Upvotes: 7