Week 49 — What is `BigInteger` and `BigDecimal`?
Question of the Week #49
What is
BigInteger
and BigDecimal
?6 Replies
Primitive numeric datatypes like
int
, long
and double
are limited in size. For example, int
can only use 32 bits while long
and double
can use 64 bits for storing data.
BigInteger
is a class representing integers of arbitrary size. It provides various mathematical operations on these numbers.
While float
and double
are able to store both very small and large numbers, they are still limited in both scale and precision. The further away from 0 a float
/double
is, the less precise it gets. These types can only store a specific number of binary digits.
On the other hand, BigDecimal
can store decimal numbers of arbitrary (but finite and limited by usable memory) size and precision.
📖 Sample answer from dan1st
BigIntgers let you use large integers, while big big decimals lets you store floating point numbers.
987654321.1938101
123456789
Submission from PNJ3.0#1519
class that can hold numbers larger than the primitive types
Submission from b.o.blox
Same thing like Integer and Decimal but can hold a bigger range.
Submission from smokeintitan
Basically this is a class in java which allow very big number to be added, sub, multiply and other operations with another very big number & here the number which is taken is taken in the string format so that the BigInteger class -> Variable can easily hold that BigIntteger.
The numbers which primitive int cant handle or can't perform the operations this BigInteger class is used to perform mathematical operations with them,
Code Example for BigIntger
package Test;
import java.math.BigInteger;
public class MyExample {
public static void main(String[] args) {
// For this example i have taken b1 and b2 same you can take according to your requirements.
BigInteger b1 = new BigInteger("123456789012345678907838748736453445877327952634565263");
BigInteger b2 = new BigInteger("123456789012345678907838748736453445877327952634565263");
// Addition
BigInteger b3 = b1.add(b2);
System.out.println("Addition is "+b3);
// Subtraction
BigInteger b4 = b1.subtract(b2);
System.out.println("Subtraction is "+b4);
// Multiplication
BigInteger b5 =b1.multiply(b2);
System.out.println("Multiplication is "+b5);
// Division
BigInteger b6 =b1.divide(b2);
System.out.println("Division is "+b6);
// Remainder
BigInteger b7 = b1.remainder(b2);
System.out.println("Remainder is "+b7);
} }
} }
⭐ Submission from anubhavagnihotrii