go – Negative big.Int turns positive after using Int64() conversion due integer overflow

Use Int.Cmp() to compare it to another big.Int value, one representing 0.

For example:

zero := new(big.Int)

switch result := diff.Cmp(zero); result {
case -1:
    fmt.Println(diff, "is less than", zero)
case 0:
    fmt.Println(diff, "is", zero)
case 1:
    fmt.Println(diff, "is greater than", zero)
}

This will output:

-34326934275868031902 is less than 0

When comparing to the special 0, instead you could also use Int.Sign() which returns -1, 0, +1 depending on the result of the comparison to 0.

switch sign := diff.Sign(); sign {
case -1:
    fmt.Println(diff, "is negative")
case 0:
    fmt.Println(diff, "is 0")
case 1:
    fmt.Println(diff, "is positive")
}

This will output:

-34326934275868031902 is negative

Try the examples on the Go Playground.

See related:

Is there another way of testing if a big.Int is 0?

Read more here: Source link