Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# How to Format Double value?

Greenhorn
Posts: 5
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

Ayyappan G

Sheriff
Posts: 21288
87
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.

Ranch Hand
Posts: 449

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.

Rob Spoor
Sheriff
Posts: 21288
87
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.

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