doumeng2637 2019-01-16 19:16
浏览 175
已采纳

fmt.Printf(“%f ”,x)将Float64舍入为Float32,但fmt.Println(x)不会

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
",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.

  • 写回答

1条回答 默认 最新

  • dtsi9484 2019-01-16 19:21
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败