Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

%v in fmt handles precision specification inconsistently for floats #5991

Closed
gopherbot opened this issue Jul 30, 2013 · 1 comment
Closed
Milestone

Comments

@gopherbot
Copy link
Contributor

by gsivek@google.com:

What steps will reproduce the problem?
http://play.golang.org/p/GM86nwT3k4

What is the expected output?
[0.123457] [0.123457] [0.12346] [0.1235]
0.100000 0.100000 0.100000 0.100000

What do you see instead?
[0.123456789] [0.123457] [0.12346] [0.1235]
0.100000 0.100000 0.1 0.1

Which compiler are you using (5g, 6g, 8g, gccgo)?
play.golang.org

Which operating system are you using?
Linux

Which version are you using?  (run 'go version')
go1.1.1

Please provide any additional information below.

The "fmt" docs (golang.org/pkg/fmt) say that %v prints the value in a default
format. For floats, this appears to be %f, and the docs state that the default precision
for %f is 6. But %v on a slice of floats or a struct containing a float may print with
higher precision (see the 0.123456789 above).

Specifying precision does truncate floats, but unlike %f, it does not add trailing
zeros: fmt.Printf("%.6v", 0.123456789) prints 0.123457 and
fmt.Printf("%.6f", 0.1) prints 0.100000, but fmt.Printf("%.6v", 0.1)
prints 0.1. Nothing in the docs suggests that %v should behave differently from %f in
this case.
@rsc
Copy link
Contributor

rsc commented Jul 30, 2013

Comment 1:

%v for a float32 or float64 is equivalent to %g, not to %f.
%f would not be a good default format because 1e100 is very large when printed with %f.
Note that unlike in C, the default precision for %g is "just enough to be precise about
which value is being printed".
Combined, these mean that the default format for a float32 or float64 is compact but
lossless.

Status changed to WorkingAsIntended.

@rsc rsc added this to the Go1.2 milestone Apr 14, 2015
@rsc rsc removed the go1.2maybe label Apr 14, 2015
@golang golang locked and limited conversation to collaborators Jun 24, 2016
This issue was closed.
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants