When I cast math.NaN() and math.MaxFloat64 to int, Why the result is different between go1.14.2 and go1.17.2?


package main

import (

func main() {
    x, y := math.NaN(), math.MaxFloat64
    fmt.Printf("%d\n", int(x))
    fmt.Printf("%d\n", int(y))

That is my test code snippet. When I run the above code use go1.14.2, the result is


but the same code run in go1.17.2, the result is


I searched the simular question: Why Is uint64 of NaN and MaxFloat64 equal in Golang?, which said that in the different hardware environment, the math.NaN() maybe different, but I run the code both in my MacOS M1 system, just golang version is different. Why the result is different between go1.14.2 and go1.17.2?


Spec: Conversions:

In all non-constant conversions involving floating-point or complex values, if the result type cannot represent the value the conversion succeeds but the result value is implementation-dependent.

You convert the floating-point value NaN to int. The valid values of the int type does not include the NaN value, so the value you convert cannot be represented by a value of type int, so the result is implementation-dependent. Basically, the spec allows it to be changed from version to version, from platform to platform. You cannot (should not) assume a specific int result for the conversion.

Answered By – icza

Answer Checked By – Terry (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.