Why do these two float64s have different values?

后端 未结 2 603
长发绾君心
长发绾君心 2020-12-17 21:50

Consider these two cases:

fmt.Println(912 * 0.01)
fmt.Println(float64(912) * 0.01)

(Go Playground link)

The second one prints 9.120

2条回答
  •  -上瘾入骨i
    2020-12-17 22:33

    The reason for the different output is that in the first case 912 * 0.01 is the multiplication of 2 untyped constant values which is of arbitrary precision, and only the result is converted to float64 when the value is passed to Println(). (See Constant expressions section of the Language specification for details.)

    In the second case float64(912) * 0.01 first 912 is converted to float64, then the untyped constant 0.01 is converted to float64 and these two values having float64 are multiplied which is not an arbitrary precision, and will not give exact result.

    Note:

    In the first case the result will be converted to float64 when passed to the Println():

    fmt.Printf("%T %v\n", 912 * 0.01, 912 * 0.01)
    

    Output:

    float64 9.12
    

    Test it on Go Playground

提交回复
热议问题