1

I have the following code:

buffer := make([]byte, 256)
conn.Read(buffer)

result:= string(buffer)
fmt.Println("Val:", result)

floatResult, _ := strconv.ParseFloat(result, 64)
fmt.Println("Val on float:", floatResult)

The output is the following:

Val: 40.385167
Val on float: 0

This seems the correct way to parse string into float64's, is there something i'm missing?

kozmo
  • 4,024
  • 3
  • 30
  • 48
Bata
  • 183
  • 2
  • 6
  • 17
  • 2
    What was `_` - did `strconv.ParseFloat` return an error? – wim Nov 25 '20 at 02:56
  • 2
    @wim oh yes: strconv.ParseFloat: parsing "-0.000000\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x 00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x 00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 .......... invalid syntax – Bata Nov 25 '20 at 02:58
  • 1
    Solved it by changing the byte array size to match my results, if i had more than that it would append giant amounts of '\x00...' – Bata Nov 25 '20 at 03:09
  • 3
    Yeah, you should always check errors in Go; sometimes it's convenient to skip it if you just want to quick test something, but if it's not working then that's the first thing to check :-) And in "real" production code you should really always check errors. – Martin Tournoij Nov 25 '20 at 03:13
  • 1) the application ignores the number of bytes read and error from the connection. Because there's no guarantee that Read fills the buffer (and it doesn't here), the count of bytes should always be used. 2) Assuming that this is a TCP connection, there's no guarantee that all of the bytes in the number are slurped up a single call to Read. The application needs to implement some sort of message framing if multiple values are sent or read to EOF if single value is sent. – Charlie Tumahai Nov 25 '20 at 03:41

1 Answers1

1

You can create new slice with len equals read bytes (look at Reader)

buffer := make([]byte, 256)
i, _ := conn.Read(buffer) // i  number of read bytes 

result:= string(buffer[:i]) // create new slice with 'len' equals number of read bytes
fmt.Println("Val:", result)

floatResult, _ := strconv.ParseFloat(result, 64)
fmt.Println("Val on float:", floatResult)

PLAYGROUND (io.Reader stub)

kozmo
  • 4,024
  • 3
  • 30
  • 48