What is the correct data type for computing in Java

Should we use double or BigDecimal for calculations in Java?

How much overhead in terms of performance for BigDecimal compared to double?

+7
java math types
source share
6 answers

For a serious financial application, BigDecimal is a must.

Depending on how many digits you need, you can use a long and decimal coefficient for visualization.

+4
source share

For general floating point calculations, use double . If you are absolutely sure that you really need arbitrary precision arithmetic (most applications do not), you can consider BigDecimal .

You will find that double significantly outperform BigDecimal (not to mention working with it) for any application where double is accurate enough.

Refresh . You commented on another answer that you want to use for a finance app. This is one area where you really should use BigDecimal , otherwise you might get unexpected rounding effects from double calculations. In addition, double values ​​have limited accuracy, and you won’t be able to accurately track pennies at the same time as millions of dollars.

+5
source share

What are the performance overheads for BigDecimal compared to double?

Lot. For example, multiplying two double numbers is one machine instruction. Multiplying two BigDecimal is probably a minimum of 50 machine instructions and has complexity O(N * M) , where M and N are the number of bytes used to represent two numbers.

However, if your application requires the calculation to be "decimal correct", you need to accept the overhead.

However (# 2) ... even BigDecimal cannot perform this calculation accurate to a real number:

  1/3 + 1/3 + 1/3 -> ? 

To perform this calculation accurately, you need to implement the Rational type; i.e. a couple of BigInteger values ​​... and some things to reduce common factors.

However (# 3) ... even the hypothetical Rational type will not give you the exact numerical representation for (say) Pi.

+3
source share

As always: it depends.

If you need precision (even for "small" numbers when representing the sum, for example), go to BigDecimal .

In some scientific applications, double may be the best choice.

+1
source share

Even in the field of finance, we cannot answer without knowing in which area. For example, if you did billions of dollars in currency conversions, where the conversion rate can be up to 5 dp You may have a double problem. While for easy adding and subtracting balances you will be fine.

If you do not need to work in a cent / penny fraction, perhaps the integral type may be more appropriate, again it depends on the size of the number.

0
source share

byte = 8 bit

short = 2 byte = 16 bit

int = 4 byte = 32 bit

long = 8 byte = 64 bit

float = 4 byte = 32 bit

double = 8 byte = 64 bit

simple calculation:

2 bytes = 1 short

2 int = 1 long

2 short = 1 int

float = int

2 float = double

-2
source share

All Articles