• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to Format Double value?  RSS feed

 
aypa genga
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!