Home > database >  strconv.ParseInt fails if number starts with 0
strconv.ParseInt fails if number starts with 0

Time:12-14

I'm currently having issues parsing some numbers starting with 0 in Go.

fmt.Println(strconv.ParseInt("0491031", 0, 64))

0 strconv.ParseInt: parsing "0491031": invalid syntax

GoPlayground: https://go.dev/play/p/TAv7IEoyI8I

I think this is due to some base conversion error, but I don't have ideas about how to fix it. I'm getting this error parsing a 5GB csv file with gocsv, if you need more details.

CodePudding user response:

Quoting from strconv.ParseInt()

If the base argument is 0, the true base is implied by the string's prefix following the sign (if present): 2 for "0b", 8 for "0" or "0o", 16 for "0x", and 10 otherwise. Also, for argument base 0 only, underscore characters are permitted as defined by the Go syntax for integer literals.

You are passing 0 for base, so the base to parse in will be inferred from the string value, and since it starts with a '0' followed by a non '0', your number is interpreted as an octal (8) number, and the digit 9 is invalid there.

Note that this would work:

fmt.Println(strconv.ParseInt("0431031", 0, 64))

And output (try it on the Go Playground):

143897 <nil>

(Octal 431031 equals 143897 decimal.)

If your input is in base 10, pass 10 for base:

fmt.Println(strconv.ParseInt("0491031", 10, 64))

Then output will be (try it on the Go Playground):

491031 <nil>
  • Related