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 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?