If you just use %f (or Print()) to format a float, the default is to
provide as many decimal places as are required to describe the value
precisely.
Andrew
Actually I'm mistaken: what I said is true of %v and %g but not %f.
Andrew
Use %v instead of %f.
Andrew
In C or C++ (and most languages that support C-style printf), %.3g
will do what you want, and this also works in go. I just mention
this, since it's not unlikely that you'll end up wanting to do the
same thing in some other language some day, and %v is specific to go.
Also, I consider using %g to be more clear, since it documents within
the string that you expect a floating-point value.
> This should be documented.
I agree.
--
David Roundy
Yes, and 1.5 is rounded towards two.
It's the standard rules.
The closest you can get is to use
s := fmt.Sprintf("%.6f", f)
n := len(s)
for n > 0 && s[n-1] == '0' {
n--
}
if n > 0 && s[n-1] == '.' {
n--
}
s = s[:n]
If you put this in a String method on your own type then
you can use it to print your values by converting them to
that type in the call to fmt.Println or any of the other printers.
Russ
You can extend the formatting behavior yourself by defining
your own floating point type that has a String or Format method.
(See godoc fmt.)
Russ