Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / November 2006

Tip: Looking for answers? Try searching our database.

Simple Java Arthimetic Help

Thread view: 
Singapore Computer Service - 04 Nov 2006 10:55 GMT
Why does

System.out.println(56.8 + 27.9)

give me 84.69999999999999, when it should give 84.7

tia
Signature

The One

Patricia Shanahan - 04 Nov 2006 11:53 GMT
> Why does
>
[quoted text clipped - 3 lines]
>
> tia

Because, according to the JLS and the API specifications, it should give
84.69999999999999

By default, Java converts doubles to strings with enough digits to
recover the exact value of the double, rather than rounding to a
reasonable number of digits. None of 56.8, 27.9, or 84.7 is exactly
representable in double.

If you really want double, but with output rounded to fewer digits, see
java.text.DecimalFormat.

If you need exact handling of bounded length decimal fractions, for
example for simple currency calculations, see java.math.BigDecimal.

Patricia
Martin Weiss - 04 Nov 2006 11:57 GMT
> Why does
>
[quoted text clipped - 3 lines]
>
> tia

It's the rounding error with doubles ..

you can either use
System.out.println(Math.round(56.8) + Math.round(27.9));
to get 85

or

System.out.println(new BigDecimal(Double.toString(56.8)).add(new
BigDecimal(Double.toString(27.9))).doubleValue());
to get the desired 84.7 :-)
Singapore Computer Service - 04 Nov 2006 12:01 GMT
Thank you patricia and martin for the clarification. Will use BigDecimal

Signature

The One

> Why does
>
[quoted text clipped - 3 lines]
>
> tia


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.