I have two variables with big numbers set as strings:
var numA = "340282366920938463463374607431768211456"
var numB = "17014118346046923173168730371588410572"
I want to be able to add and subtract these kinds of large string numbers in Go.
I know I need to use math/big
but I still can not for the life of me figure out how, so any example help will be greatly appreciated!
You may use big.NewInt()
to create a new big.Int
value initialized with an int64
value. It returns you a pointer (*big.Int
). Alternatively you could simply use the builtin new()
function to allocate a big.Int
value which will be 0
like this: new(big.Int)
, or since big.Int
is a struct type, a simple composite literal would also do: &big.Int{}
.
Once you have a value, you may use Int.SetString()
to parse and set a number given as string
. You can pass the base of the string number, and it also returns you a bool
value indicating if parsing succeeded.
Then you may use Int.Add()
and Int.Sub()
to calculate the sum and difference of 2 big.Int
numbers. Note that Add()
and Sub()
write the result into the receiver whose method you call, so if you need the numbers (operands) unchanged, use another big.Int
value to calculate and store the result.
See this example:
numA := "340282366920938463463374607431768211456"
numB := "17014118346046923173168730371588410572"
ba, bb := big.NewInt(0), big.NewInt(0)
if _, ok := ba.SetString(numA, 10); !ok {
panic("invalid numA")
}
if _, ok := bb.SetString(numB, 10); !ok {
panic("invalid numB")
}
sum := big.NewInt(0).Add(ba, bb)
fmt.Println("a + b =", sum)
diff := big.NewInt(0).Sub(ba, bb)
fmt.Println("a - b =", diff)
Output (try it on the Go Playground):
a + b = 357296485266985386636543337803356622028
a - b = 323268248574891540290205877060179800884