简体   繁体   中英

Golang cannot convert []byte("1575455669.4") to float64 using math.Float64frombits

I have the following code:

x := []byte("1575455669.4")
bits := binary.LittleEndian.Uint64(x)
f := math.Float64frombits(bits)

On calling fmt.Println(f) I expect 1.5754556694e+09 . But instead I end up with 1.451098468672448e-47

When I try the same conversion through strconv.ParseFloat(string(x), 64) I get the correct result. What am I doing wrong here?

This:

x := []byte("1575455669.4")

will give you the (UTF-8 encoded) bytes of the "1575455669.4" string. This has nothing to do with the memory representation of the floating point number 1575455669.4 which uses the IEEE 754 standard. But what you do next would assume just that:

bits := binary.LittleEndian.Uint64(x)
f := math.Float64frombits(bits)

You have a number given as its base-10 string representation, you have to use strconv.ParseFloat(string(x), 64) to parse it and have it as a float64 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM