Handling Very Large Numbers


You need to handle integer numbers larger than Long.MAX_VALUE or floating-point values larger than Double.MAX_VALUE.


Use the BigInteger or BigDecimal values in package java.math :

// BigNums.java 
System.out.println("Here's Long.MAX_VALUE: " + Long.MAX_VALUE); 
BigInteger bInt = new BigInteger("3419229223372036854775807"); 
System.out.println("Here's a bigger number: " + bInt); 
System.out.println("Here it is as a double: " + bInt.doubleValue(  ));

Note that the constructor takes the number as a string. Obviously you couldn’t just type the numeric digits, since by definition these classes are designed to represent numbers larger than will fit in a Java long.


Both BigInteger and BigDecimal objects are immutable; that is, once constructed, they always represent a given number. That said, there are a number of methods that return new objects that are mutations of the original, such as negate( ) , which returns the negative of the given BigInteger or BigDecimal. There are also methods corresponding to most of the Java language built-in operators defined on the base types int/long and float/double. The division method makes you specify the rounding method; consult a book on numerical analysis for details. Here is a simple stack-based calculator using BigDecimal as its numeric data type:

import java.math.BigDecimal; import java.util.Stack; /** A trivial reverse-polish stack-based calculator for big numbers */ public class BigNumCalc ...

Get Java Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.