Occasionally, we cast float64
to int32
directly by mistake in Golang
raw = 529538871408
fv = float64(raw)
fmt.Println(raw)
fmt.Println(fv)
fmt.Println(int32(fv))
Output
529538871408
5.29538871408e+11
-2147483648
Why int32(fv)
given a negative number?
As we know, both long
in C++ and float64
in Golang is a 64 bit IEEE 754 double precision. So we try same code in C++
int64_t iv = 529538871408;
std::cout << iv << std::endl;
double fv = double(iv);
std::cout << fv << std::endl;
int32_t i32v = int32_t(fv);
std::cout << i32v << std::endl;
Output:
529538871408
5.29539e+11
2147483647
The result is 2147483647
, why? Is anything am I missing? or something wrong?