Reputation: 21
When I compare the following not equal length strings in Go, the result of comparison is not right. Can someone help?
i := "1206410694"
j := "128000000"
fmt.Println("result is", i >= j, i, j )
The output is:
result is false 1206410694 128000000
The reason is probably because Go does char by char comparison starting with the most significant char. In my case these strings represent numbers so i is larger than j. So just wonder if someone can help with explaining how not equal length strings are compared in go.
Upvotes: 1
Views: 639
Reputation: 63139
The reason is probably because Go does char by char comparison starting with the most significant char.
This is correct.
If they represent numbers, then you should compare as them as numbers. Parse / convert them to int
before comparing:
ii, _ := strconv.Atoi(i)
ij, _ := strconv.Atoi(j)
Edit: And yes, @JimB is totally right. If you are not 100% sure that the conversion will succeed, please do not ignore the errors.
Upvotes: 4