Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

Handling Very Large Numbers

Problem

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

Solution

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.

Discussion

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata