Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

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

Is there a really large variable type I can use in Java to store huge numbers (up to around forty digits)?

long's maximum value is 9223372036854775807, which is 19 digits -- not nearly large enough.

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

EDIT

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...