在 Java 中存储一个比 long 类型长的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21724945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:19:49  来源:igfitidea点击:

Store a number that is longer than type long in Java

java

提问by user2773145

How can I store a number that is longer than the long type (MAX: 9223372036854775807) in Java?

如何在 Java 中存储比 long 类型(MAX:9223372036854775807)长的数字?

For example the number 9223372036854775820.

例如号码 9223372036854775820。

Thanks in advance.

提前致谢。

回答by Kevin Bowersox

You must use BigIntegerto store values that exceed the max value of long.

您必须使用BigInteger来存储超过 long 最大值的值。

回答by kai

Use BigIntegerif you work with a long and use BigDecimalif you work with floatingpoint numbers. The BigIntegercan as big as you want, till there is not enough RAM.

使用BigIntegerlong 时使用,使用BigDecimal浮点数时使用。该BigInteger罐那么大,只要你想,直到没有足够的RAM。

Example:

例子:

    BigInteger bd = new BigInteger("922337203685477582012312321");
    System.out.println(bd.multiply(new BigInteger("15")));
    System.out.println(bd);

Output:

输出:

13835058055282163730184684815
922337203685477582012312321

But have to use the BigIntegermethods to do calculations and in the example you see that BigIntegeris immutable.

但是必须使用这些BigInteger方法进行计算,并且在示例中您会看到它BigInteger是不可变的。

回答by PaolaG

You can use a BigInteger type.

您可以使用 BigInteger 类型。