a go lang big integer lib
refer to java BigInteger
In the go language, we know that there are only
byte,int32, andint64for integers, float have onlyfloat32andfloat64. Sometimes we need to use large number operations according to your needs. Thebigpackage in go withNewIntandNewFloat, but there are fewer APIs, and only basic types can be used for initialization. You cannot use a string for initialization. So I developedgo-biggerthat reference to Java's large number classes and provided a rich API calls.
go get github.com/sineycoder/go-bigger
In BigInteger, we cached |x| < 16 BigInteger
you can use
big_integer.NewBigIntegerInt(1231221)orbig_integer.ValueOf(6782613786431)to initialize a BigInteger. If useValueOfand within 16, it returns a cache BigInteger.
func main() {
a := bigger.BigIntegerValueOf(6782613786431)
b := bigger.BigIntegerValueOf(-678261378231)
res := a.Add(b)
fmt.Println(res.String())
}
// result:6104352408200
func main() {
a := bigger.BigIntegerValueOf(6782613786431)
b := bigger.BigIntegerValueOf(-678261378231)
res := a.Subtract(b)
fmt.Println(res.String())
}
// result:7460875164662
func main() {
a := bigger.BigIntegerValueOf(6782613786431)
b := bigger.BigIntegerValueOf(-678261378231)
res := a.Divide(b)
fmt.Println(res.String())
}
// result: -10
func main() {
a := bigger.BigIntegerValueOf(6782613786431)
b := bigger.BigIntegerValueOf(-678261378231)
res := a.Multiply(b)
fmt.Println(res.String())
}
// result:-4600384974793271546583561
you can use
bigger.NewBigDecimalString("123123.111")orbigger.BigDecimalValueOf(6782613786431.111)to initialize a BigInteger. If useBigDecimalValueOfand whithin 10, it returns a chache BigDecimal.
func main() {
a := bigger.BigDecimalValueOf(6782613786431)
b := bigger.BigDecimalValueOf(-678261378231)
res := a.Add(b)
fmt.Println(res.String())
}
// result:6104352408200
func main() {
a := bigger.BigDecimalValueOf(6782613786431)
b := bigger.BigDecimalValueOf(-678261378231)
res := a.Subtract(b)
fmt.Println(res.String())
}
// result:7460875164662
func main() {
a := bigger.BigDecimalValueOf(6782613786431)
b := bigger.BigDecimalValueOf(-678261378231)
res := a.Divide(b, 12, bigger.ROUND_HALF_UP)
fmt.Println(res.String())
}
// result: -10.000000006076
func main() {
a := bigger.BigDecimalValueOf(6782613786431)
b := bigger.BigDecimalValueOf(-678261378231)
res := a.Multiply(b)
fmt.Println(res.String())
}
// result:-4600384974793271546583561
if you want to set a precision, you can use setScale(). Remenber: The return value must be assigned. (e.g. res = res.setScale(12, bigger.ROUND_HALF_UP))
The details please visit this WebSite:https://blog.csdn.net/a568283992/article/details/119698329