What variable type can I use to hold huge numbers (30+ digits) in java?

谁说胖子不能爱 提交于 2019-11-28 20:32:55

You can use BigInteger class.

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);

Output:

Sum : 3677593528178171109762168924892318

Product : 1938839471287900434078965247064711159607977007048190357000119602656

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()));

Output:

$123,234,545.48

You can try using the BigInteger class for operations with really huge integer numbers.

For operations with floating numbers, Java provides the BigDecimal class, which can be useful, as well.

Joni

For calculations with exponents, like you would use in a calculator, you should use BigDecimal. The problem with BigInteger is that it only handles integers (no fractional numbers) and that for really big numbers like 10^100 it stores all the zeros, using a lot of memory, instead of using a format based on scientific notation.

You could alternatively use the floating point number type double, which gives you a large range of values, low memory usage and fast operations. But because of rounding issues and limited precision (around 16 decimal digits), I wouldn't recommend using it unless you really know what you're doing.

You can use float ^e

so you could have

0.55342663552772737682136182736127836782163 * 10^e

Calculators are mostly use that, too.

This is for all bigger numbers above 15 since using int blows it. You may want to find the factorial of 50 or 100 0r 500.

// Recursive version of the Fat factorial for bigger numbers ex: Factorial of 500     
BigInteger fatFactorial(int b) {
    if (BigInteger.ONE.equals(BigInteger.valueOf(b))
        || BigInteger.ZERO.equals(BigInteger.valueOf(b))) {
            return BigInteger.ONE;
    } else {
        return BigInteger.valueOf(b).multiply(fatFactorial(b - 1));
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!