问题描述
我可以在Java中使用一个非常大的变量类型来存储大量数字(最多大约四十个数字)吗?
Is there a really large variable type I can use in Java to store huge numbers (up to around forty digits)?
long
的最大值是9223372036854775807,这是19位数 - 不够大。
long
's maximum value is 9223372036854775807, which is 19 digits -- not nearly large enough.
我正在尝试创建一个可以处理大数字的计算器,因为现在大多数只能容纳10位数左右,我想要用数字进行精确计算更大幅度
I'm trying to create a calculator that can handle large numbers, because most nowadays can only hold an insufficient 10 digits or so, and I want want accurate calculations with numbers of a much larger magnitude
编辑
感谢您的回答。对于大整数,我可以使用 BigInteger
,唯一的限制是计算机的内存(应该足够)。对于小数,我将使用 float
^ e,如@WebDaldo建议,或 BigDecimal
(类似于BigInteger),正如@kocko建议的那样。
Thanks for the answers. I can use BigInteger
for big integers, the only limit being the computer's memory (should be sufficient). For decimals, I'll use float
^e, as @WebDaldo suggested, or BigDecimal
(similar to BigInteger), as @kocko suggested.
推荐答案
你可以使用类。
BigInteger bi1 = new BigInteger("637824629384623845238423545642384");
BigInteger bi2 = new BigInteger("3039768898793547264523745379249934");
BigInteger bigSum = bi1.add(bi2);
BigInteger bigProduct = bi1.multiply(bi2);
System.out.println("Sum : " + bigSum);
System.out.println("Product : " + bigProduct);
输出:
产品:1938839471287900434078965247064711159607977007048190357000119602656
Product : 1938839471287900434078965247064711159607977007048190357000119602656
我应该提到,非常适合金额计算与 double 比较。
I should mention BigDecimal, which is excellent for amount calculations compare to double.
BigDecimal bd = new BigDecimal("123234545.4767");
BigDecimal displayVal = bd.setScale(2, RoundingMode.HALF_EVEN);
NumberFormat usdFormat = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(usdFormat.format(displayVal.doubleValue()));
输出:
这篇关于我可以用什么变量类型来保存java中的大数(30+位)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!