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

strconv: FormatFloat(38.675, 'f', -1, 64) does not give the most precise decimal approximation #17997

Closed
mrwonko opened this issue Nov 21, 2016 · 3 comments

Comments

@mrwonko
Copy link

mrwonko commented Nov 21, 2016

What version of Go are you using (go version)?

1.7

What operating system and processor architecture are you using (go env)?

Playground

What did you do?

strconv.FormatFloat(38.675, 'f', -1, 64)
https://play.golang.org/p/r2SL1x_Uu6

What did you expect to see?

38.675 doesn't have an exact float64 representation; I expected 38.6749999999999971578290569595992565155029296875.

What did you see instead?

38.675

@ALTree
Copy link
Member

ALTree commented Nov 21, 2016

The special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly.

The documentation doesn't say that FormatFloat will print the most precise decimal approximation. What it does say is that it'll output just enough digits so that ParseFloat will return f exactly.

@mrwonko
Copy link
Author

mrwonko commented Nov 21, 2016

So "exactly" in this context means a decimal representation whose closest float64 representation is the correct one? I see.

@mrwonko mrwonko closed this as completed Nov 21, 2016
@rsc
Copy link
Contributor

rsc commented Nov 22, 2016

Note that for what you expect, you can use:

strconv.FormatFloat(38.675, 'g', 1000, 64)

@golang golang locked and limited conversation to collaborators Nov 22, 2017
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

4 participants