[英]fmt.Printf("%f\n",x) rounds a Float64 to Float32, but fmt.Println(x) doesn't
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
我正在使用字典进行一些测试,为此,我以某种格式从数据库中打印出我想要的 Float64 值,以便将它们复制并粘贴到我的测试结构数组中,但是当我的测试失败时,我注意到这些值不同,但是仅由
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.我检查了文档并没有看到任何表明 Float64 有特殊符号或 %f 将 Float64 替换为 Float32 的内容,但是,当我使用
%v
或%g
并且文档指定它们时我没有遇到问题将在适当的时候使用%f
。
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.当我使用
%.12f
指定精度为 12 时,我也没有遇到问题,但文档中没有指定默认精度。
Why does this happen?为什么会发生这种情况?
EDIT: This is the same issue as the duplicate, but I believe Adrien's explanation about it is more detailed.编辑:这与副本相同,但我相信 Adrien 对此的解释更详细。
The default precision for %e, %f and %#g is 6;
%e、%f 和 %#g 的默认精度为 6; for %g it is the smallest number of digits necessary to identify the value uniquely.
对于 %g,它是唯一标识值所需的最小位数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.