Новости из мира ПК
12 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд

Java biginteger max value

BigDecimal and BigInteger in Java

Last modified: July 20, 2019

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

In the 9 years of running Baeldung, I’ve never, ever done a «sale».
But. we’ve also not been through anything like this pandemic either.
And, if making my courses more affordable for a while is going to help a company stay in business, or a developer land a new job, make rent or be able to provide for their family — then it’s well worth doing.
Effective immediately, all Baeldung courses are 33% off their normal prices!
You’ll find all three courses in the menu, above, or here.

1. Overview

In this tutorial, we will demonstrate BigDecimal and the BigInteger classes.

We’ll describe the two data types, their characteristics, and their usage scenarios. We’ll also briefly cover the various operations using the two classes.

2. BigDecimal

BigDecimal represents an immutable arbitrary-precision signed decimal number. It consists of two parts:

  • Unscaled value – an arbitrary precision integer
  • Scale – a 32-bit integer representing the number of digits to the right of the decimal point

For example, the BigDecimal 3.14 has the unscaled value of 314 and the scale of 2.

We use BigDecimal for high-precision arithmetic. We also use it for calculations requiring control over scale and rounding off behavior. One such example is calculations involving financial transactions.

We can create a BigDecimal object from String, character array, int, long, and BigInteger:

We can also create BigDecimal from double:

However, the result, in this case, is different from expected (that is 0.1). This is because:

  • the double constructor does an exact translation
  • 0.1 does not have an exact representation in double

Therefore, we should use the String constructor instead of the double constructor.

Читать еще:  Java reader class

In addition, we can convert double and long to BigInteger using the valueOf static method:

This method converts double to its String representation before converting to BigDecimal. In addition, it may reuse object instances.

Hence, we should use the valueOf method in preference to the constructors.

3. Operations on BigDecimal

Just like the other Number classes (Integer, Long, Double etc.), BigDecimal provides operations for arithmetic and comparison operations. It also provides operations for scale manipulation, rounding and format conversion.

It does not overload the the arithmetic (+, -, /, *) or logical (>.

There are two classes which control rounding behavior – RoundingMode and MathContext.

The enum RoundingMode provides eight rounding modes:

  • CEILING – rounds towards positive infinity
  • FLOOR – rounds towards negative infinity
  • UP – rounds away from zero
  • DOWN – rounds towards zero
  • HALF_UP – rounds towards “nearest neighbor” unless both neighbors are equidistant, in which case rounds up
  • HALF_DOWN – rounds towards “nearest neighbor” unless both neighbors are equidistant, in which case rounds down
  • HALF_EVEN – rounds towards the “nearest neighbor” unless both neighbors are equidistant, in which case, rounds towards the even neighbor
  • UNNECESSARY – no rounding is necessary and ArithmeticException is thrown if no exact result is possible

HALF_EVEN rounding mode minimizes the bias due to rounding operations. It is frequently used. It is also known as the banker’s rounding.

MathContext encapsulates both precision and rounding mode. There are few predefined MathContexts:

  • DECIMAL32 – 7 digits precision and a rounding mode of HALF_EVEN
  • DECIMAL64 – 16 digits precision and a rounding mode of HALF_EVEN
  • DECIMAL128 – 34 digits precision and a rounding mode of HALF_EVEN
  • UNLIMITED – unlimited precision arithmetic
Читать еще:  Java desktop application

Using this class, we can round a BigDecimal number using specified precision and rounding behavior:

Now, let’s examine the rounding concept using a sample calculation.

Let’s write a method to calculate the total amount to be paid for an item given a quantity and unit price. Let’s also apply a discount rate and sales tax rate. We round the final result to cents by using the setScale method:

Now, let’s write a unit test for this method:

5. BigInteger

BigInteger represents immutable arbitrary-precision integers. It is similar to the primitive integer types but allows arbitrary large values.

It is used when integers involved are larger than the limit of long type. For example, the factorial of 50 is 30414093201713378043612608166064768844377641568960512000000000000. This value is too big for an int or long data type to handle. It can only be stored in a BigInteger variable.

It is widely used in security and cryptography applications.

We can create BigInteger from a byte array or String:

In addition, we can convert a long to BigInteger using the static method valueOf:

6. Operations on BigInteger

Similar to int and long, BigInteger implements all the arithmetic and logical operations. But, it does not overload the operators.

It also implements the corresponding methods from Math class: abs, min, max, pow, signum.

We compare the value of two BigIntegers using the compareTo method:

We perform arithmetic operations by calling the corresponding methods:

As BigInteger is immutable, these operations do not modify the existing objects. Unlike, int and long, these operations do not overflow.

BigInteger has the bit operations similar to int and long. But, we need to use the methods instead of operators:

Читать еще:  Как создать игру на javascript

It has additional bit manipulation methods:

BigInteger provides methods for GCD computation and modular arithmetic:

It also has methods related to prime generation and primality testing:

7. Conclusion

In this quick tutorial, we explored the classes BigDecimal and BigInteger. They are useful for advanced numerical computations where the primitive integer types do not suffice.

As usual, the full source code can be found over on GitHub.

Ссылка на основную публикацию