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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据