aspose file tools*
The moose likes Java in General and the fly likes comparision between double  and long Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "comparision between double  and long" Watch "comparision between double  and long" New topic
Author

comparision between double and long

Rizwan Mohammad
Ranch Hand

Joined: Sep 02, 2005
Posts: 445
why 1234567891.00000001 == (long)1234567891.00000001 returns true even though they are fals
but 123456789.00000001 == (long)123456789.00000001 returns true..

Also,
How do i know whether one number is pure decimal or number.
What I mean pure decimal number is after point(.) if it has 00001 or some other number is pure decimal. And I want to consider 1000.000 (all 0 after point) as long. How do I make that difference without writing some custom function. Is that possible?


Rizwan
SCJA, SCJP, SCWCD, SCBCD, SCDJWS.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

why 1234567891.00000001 == (long)1234567891.00000001 returns true even though they are fals
but 123456789.00000001 == (long)123456789.00000001 returns true..


It's an issue with precision. Floating point values are not that accurate in terms of precision.

Actually, you didn't even need to cast it to a long value...

"123456789.00000001 == 123456789.0" should return true.

Henry
[ July 21, 2006: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rizwan Mohammad
Ranch Hand

Joined: Sep 02, 2005
Posts: 445
123456789.00000001 == 123456789.0" should return true.


But I want them as false
123456789.00000001 == 123456789.0000000 should return me false. How do I do that?
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
What about BigDecimal?

Rizwan Mohammad
Ranch Hand

Joined: Sep 02, 2005
Posts: 445
If you remove string and give numbers as double instead of string it says equal(compare method returns 0)
BigDecimal bd1 = new BigDecimal(1234567891.00000001);
BigDecimal bd2 = new BigDecimal(1234567891);
bd1.compareTo(bd2) returns 0. and prints BD1 == BD2
Edwin Dalorzo
Ranch Hand

Joined: Dec 31, 2004
Posts: 961
What you need to understand, Rizwan my comrade, is that this number 123456789.00000001 cannot be expressed as double, simply because double cannot hold that small precision number. Then it simply discards it the extra precision.

So, if you create the BigDecimal using the same double value that is causing you trouble, you will get the same result back again.

Use Strings to hold the decimal value and then use the compareTo method to determine if one number is bigger, smaller or equal to the other.

Be careful with the equals() method. Read the javadoc API about it.
[ July 21, 2006: Message edited by: Edwin Dalorzo ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: comparision between double and long