This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Double data type issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Double data type issue " Watch "Double data type issue " New topic
Author

Double data type issue

Kasun Athukorala
Greenhorn

Joined: Jun 14, 2011
Posts: 18
Guys,

This is my code....



double ctr = 0.00; //Declaration

ctr = 62176457141856560629502157223196586755079324193331.00;

out.printf("%50.2f",bla);



when i print ctr this is my output,

62176457141856560000000000000000000000000000000000.00

I'm using NetBeans 7, and windows xp sp3.
why isn't it giving the same input value??
How can i get the same output as the input??
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10906
    
  12

With a double, you can't. there are well-defined limitations on how precise they can be, and you have gone way beyond the limits.

You may want to check out item #20 on this page.

If you really need that degree of precision, you may want to check out the BigDecimal class.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19538
    
  16

Kasun Athukorala wrote:why isn't it giving the same input value??

Because double only has 64 bit to store its information. Your number is too large and it gets truncated.

How can i get the same output as the input??

By using BigDecimal. That's the only data type in Java that's accurate enough. Note that you should use the constructor that takes a String; don't create one from a double because the truncation will then happen before the BigDecimal is created.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Kasun Athukorala
Greenhorn

Joined: Jun 14, 2011
Posts: 18
fred rosenberger wrote:With a double, you can't. there are well-defined limitations on how precise they can be, and you have gone way beyond the limits.

You may want to check out item #20 on this page.

If you really need that degree of precision, you may want to check out the BigDecimal class.



Thanks a lot for the solution mate........

Thank you both of you.........
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Double data type issue
 
Similar Threads
Getting Junk Values While overridding jspInit()
Thread code produces different output
Super class constructor calls derived class overridden method?
read content of text file then convert to decimal number
problems with batch update