-6

I was working on some tests with dictionaries, to do this I print out the Float64 values I want from a database in a format to copy and paste them into my test struct array, but when my tests failed I noticed that the values differ, but only by 0.0000000000002

Then, to check the value I wrote the following in a loop:

fmt.Printf("%f\n",value)
fmt.Println(value)

And I got the following values back:

702.200000
702.1999999999998
5683.090000
5683.089999999998
975.300000
975.3

I checked the docs and saw nothing that indicates that there's special notation for Float64 or that %f will replace Float64 for a Float32, however, I don't get the problem when I use %v or %g and the docs specify that they'll use %f when appropriate.

I don't get the problem when I specify a precision of 12 using %.12f either, but no default precision is specified in the docs.

Why does this happen?

EDIT: This is the same issue as the duplicate, but I believe Adrien's explanation about it is more detailed.

Devyzr
  • 299
  • 5
  • 13
  • Possible duplicate of [Does converting a string to a float lose precision?](https://stackoverflow.com/questions/54169068/does-converting-a-string-to-a-float-lose-precision) – Jonathan Hall Jan 17 '19 at 07:10

1 Answers1

3

From the docs:

The default precision for %e, %f and %#g is 6; for %g it is the smallest number of digits necessary to identify the value uniquely.

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • Ah, crud. I don't know why I didn't see that. I went through the docs to avoid exactly this. However, it doesn't explain why the precision changes when I use %v or %g, as stated in the question. – Devyzr Jan 16 '19 at 19:28
  • 1
    The rest of the docs do, specifically that `%v` uses the "default format" which for "float32, complex64, etc" is `%g`, and that (regarding default precision) "for %g it is the smallest number of digits necessary to identify the value uniquely" – Adrian Jan 16 '19 at 19:51
  • Thanks a lot Adrian! I don't know how I missed this, I'll blame the lack of morning coffee. – Devyzr Jan 16 '19 at 21:14
  • 1
    `fmt` has very thorough docs but they could definitely use a rewrite. It's full of internal references with no anchor links and details buried in the middle of a paragraph. It's unfortunate given how much use the package gets. – Adrian Jan 17 '19 at 14:02