posted 9 years ago

Hi,

i have two double values which are then multiplied.

Can you please tell me how to get the exact values.

Below is the example :

4069976.23 * 1815496.43 = 7389027315749.8589

the code :

double x = 4069976.23d;

double y = 1815496.43d;

double z =x*y;

System.out.println("z :"+z);

the result that i get is

z :7.389027315749858E12

how can i get the exact answer 7389027315749.8589

Thanks in advance,

Ayyappan G

i have two double values which are then multiplied.

Can you please tell me how to get the exact values.

Below is the example :

4069976.23 * 1815496.43 = 7389027315749.8589

the code :

double x = 4069976.23d;

double y = 1815496.43d;

double z =x*y;

System.out.println("z :"+z);

the result that i get is

z :7.389027315749858E12

how can i get the exact answer 7389027315749.8589

Thanks in advance,

Ayyappan G

posted 9 years ago

Both float and double are simply not that precise. Sure, they can store very large numbers, but part of the precision is lost.

java.math.BigDecimal, although slower, does not have this problem.

java.math.BigDecimal, although slower, does not have this problem.

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions

posted 9 years ago

Big Decimal is less convenient than using a primitive arithmetic type, and it’s slower too. An alternative to using BigDecimal is to use int or long, depending on the amounts involved, and to keep track of the decimal point yourself.

If performance is of the essence and the quantities aren’t too big, use int or long. If the quantities don’t exceed nine decimal digits, you can use int; if they don’t exceed eighteen digits, you can use long. If the quantities might exceed eighteen digits, you must use BigDecimal.

Rob Prime wrote:Both float and double are simply not that precise. Sure, they can store very large numbers, but part of the precision is lost.

java.math.BigDecimal, although slower, does not have this problem.

Big Decimal is less convenient than using a primitive arithmetic type, and it’s slower too. An alternative to using BigDecimal is to use int or long, depending on the amounts involved, and to keep track of the decimal point yourself.

If performance is of the essence and the quantities aren’t too big, use int or long. If the quantities don’t exceed nine decimal digits, you can use int; if they don’t exceed eighteen digits, you can use long. If the quantities might exceed eighteen digits, you must use BigDecimal.

posted 9 years ago

But you will need another int to store the number of decimals, since this is not fixed. Simply using an int or long is not sufficient. In the end, you'll probably end up with your own version of BigDecimal.

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions

With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |