How to use Java BigDecimal to display floating point numbers

The Java class BigDecimal makes it possible to process complex floating point numbers with precision. Once they’ve been created, you can apply different methods to them. The structure of the syntax is always the same, so it’s easy to quickly familiarise yourself with the class.

What is Java BigDecimal?

Java BigDecimal allows you to accurately display and process complex floating point numbers of theoretically any size. This article will show you different methods for using this class, be it for rounding, arithmetic or format conversion. You’ll also learn how to implement it for hashing and for precise, sophisticated comparisons.

Java BigDecimal consists of a 32-bit integer scale and an unscaled integer value with optional precision. In this case, ‘scale’ means the number of digits after the decimal point, provided they’re greater than or equal to zero. However, if the value is less than zero, it is multiplied by 10^(-scale). The size of the class is limited only by the computer’s memory. Though this is more of a theoretical consideration, as it’s unlikely that a program will create a number that exceeds its available memory. BigDecimal in Java is intended exclusively for floating point numbers, while the BigInteger class is used for processing integers.

Web Hosting
Secure, reliable hosting for your website
  • 99.9% uptime and super-fast loading
  • Advanced security features
  • Domain and email included

What is the class needed for?

Java BigDecimal’s level of precision isn’t needed for every scenario. But there are situations where its precision is invaluable. For example, it serves its purpose well in e-commerce transactions, where calculations can be impacted by even the smallest decimal place. The class is also used to conduct precise static analyses. Programs used for the control and navigation of aeroplanes or rockets rely on the class, as does the medical segment. In other fields, the levels of precision offered by Java BigDecimal provides the best possible security.

How is an object created?

To use BigDecimal in Java, you’ll need to first import the class into your Java program. Once you’ve done that, you can declare an object of this class. Next, create the desired value as an argument and pass this to the appropriate Java constructor. Once you’ve completed this process, you can use BigDecimals in Java. Within the class, you’ll find various methods, which we’ll explain in more detail in the following section. First, we’re going to import the class and declare two BigDecimal objects:

/ / Your Java program for the BigDecimal class
import java.math.BigDecimal;
public class BigDecimalExample
{
	public static void main(String[] args)
	{
		/ / Create two new BigDecimals
		BigDecimal ExampleOne =
			new BigDecimal ("1275936001.744297361");
		BigDecimal ExampleTwo =
			new BigDecimal ("4746691047.132719503");
	}
}
java

Now you can use these objects with the methods for the BigDecimal class.

Examples for Java BigDecimal

Once you have created the objects, you can use different methods to use the objects and perform operations. Let’s look at a few examples to show you how this works. The output is initiated using the Java command System.out.println().

Adding two BigDecimals

If you want to add two BigDecimals in Java, you need to use the add() method. To do this, store the two values that you want to calculate the sum for. In our example, the value ExampleOne will be added to the value ExampleTwo.

ExampleOne =
ExampleOne.add(ExampleTwo);
System.out.println ("Here is the result: " + ExampleOne);
java

Subtract numbers

To subtract two values from each other, you need the subtract() method. In the next example, we subtract ExampleTwo from ExampleOne.

ExampleOne =
ExampleOne.subtract(ExampleTwo);
System.out.println ("Here is the result: " + ExampleOne);
java

Multiply values

The method you use to multiply two BigDecimals in Java works similarly. It’s called multiply(). To multiply ExampleTwo by ExampleOne, use the following code:

ExampleOne =
ExampleOne.multiply(ExampleTwo);
System.out.println ("Here is the result: " + ExampleOne);
java

Dividing numbers

If you want to divide two BigDecimal objects in Java, use the divide() method. This follows the same syntax as the other examples and looks like this:

ExampleOne =
ExampleOne.divide(ExampleTwo);
System.out.println ("Here is the result: " + ExampleOne);
java

However, this only works if the result is exact or an integer. If this is not the case, the following error message will be output: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.. This describes a runtime error. To avoid this, there are various rounding options for the divide() method, which can be transmitted via java.math.RoundingMode. You can choose from the following constants:

Constant Function
CEILING Rounds to positive infinity
DOWN Rounds to 0
FLOOR Rounds to negative infinity
HALF_DOWN Rounds to the nearest neighbouring number and the opposite of 0 if both are equidistant
HALF_EVEN Rounds to the next neighbouring number and to the next even number if both are equidistant
HALF_UP Rounds to the nearest neighbouring number and in the direction of 0, provided they are both the same distance away
UNNECESSARY Omits rounding and only performs exact operations; can only be used if the division is exact
UP Rounds away from 0

Overview of the most important methods

Now that you’ve learned how to use BigDecimal in Java, here’s an overview of some of the most important methods you can use with it.

Method Function
abs() Returns a BigDecimal with its absolute value
add() Returns a BigDecimal whose value is composed of (this + Addend)
divide() Output value results from (this / Divisor)
max(BigDecimal val) Outputs the maximum of the BigDecimal
min(BigDecimal val) Outputs the minimum of the BigDecimal
movePointLeft(int n) Outputs a BigDecimal where the decimal point has been moved to the left by the value ‘n’
movePointRight(int n) Outputs a BigDecimal where the decimal point has been moved to the right by the value ‘n’
multiply(BigDecimal multiplicand, MathContext mc) Returns a value that results from (this * multiplicand)
Tip

In our Digital Guide, you can learn more about Java. You can read about Java operators, the differences between Java and JavaScript or find out how Java and Python compare.

Was this article helpful?
Page top