Link to home
Start Free TrialLog in
Avatar of applekanna
applekanna

asked on

java double

program code -->
                  float a1 = 1800 * 0.07f;
                  System.out.println("VALue  =  1800 *x =" +  a1) ;
                  double a2 = 1800 *0.07;
                  System.out.println("VALue  =  1800 *x =" +  a2) ;

output -->

VALue  =  a800 *x =126.0
VALue  =  a800 *x =126.00000000000001

I know float is 32 bytes and double is 64 bytes.
Can anyone explain the difference...... y i get this difference 126 and 126.00000
Thank  you
Avatar of surajdeo
surajdeo
Flag of Mexico image

this is because float can display only upto 7 digits after decimal while double can display upto 16 digit.
Avatar of applekanna
applekanna

ASKER

that is correct but isnt 1800*0.7 = 126
Hi, applekanna!

Yes, there's a bug here. I've experienced it too one day. This is all because of double type. If you switch to float the problem will be resolved. I hope float is good enough for your calculations...

Regards!
ASKER CERTIFIED SOLUTION
Avatar of grim_toaster
grim_toaster

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CEHJ
It's not a bug - floating point values are not exact beyond a certain scale. Float only hides the problem becuase it's *less* precise. If you want precision, use BigDecimal:

BigDecimal result = new BigDecimal("1800").multiply(new BigDecimal("0.07"));
System.out.println(result);
Sorry, a question of mine (actually this topic is of a certain interest for me too and I can award points...)

Is this a known bug? Are there any patches available? Is it common for all JVM-implementations or just the Sun's one?

And if some official links available could you post them?

Regards!
See above. AFAIK, it's a problem that occurs at the hardware level.
Have a look a t a copy of Effective Java Programming, chapter 7, downloadable as a sample chapter at:

http://java.sun.com/docs/books/effective/chapters.html
Thanks guys! I got the main idea... Your points are here:

https://www.experts-exchange.com/questions/20800340/Points-for-CEHJ-and-grim-toaster.html

Regards!
heh, one more comment:

System.out.println (1800*0.007) gives 12.6 :)

Regards!
This may occur because 0.7 has infinite binary reprezentation at far places...
Or because you've used up one place of precision, so the ending 1 has been gobbled up
Hi applekanna,

<<that is correct but isnt 1800*0.7 = 126 >>

for 1800*0.7 I am getting answer 1260.0.

I checked this with J2SDK1.3 using IBM Webshpere Studio Aplication Developer.

Can u pl tell me what the exact problem?

regards,
suraj deo
Sorry suraj,

It was a typo. it is actually 1800*0.07.
I tried 1800*0.7 and it worked fine too.

Thank you all for you response.