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 / General / April 2007

Tip: Looking for answers? Try searching our database.

stupid problem with variable showing

Thread view: 
bacrobidia@gmail.com - 21 Apr 2007 15:52 GMT
i'm writing really frustrated by this stupid problem i try to print a
double (or maybe float) variable with system.out.println but it shows
only 0.0!!!

this is the code

double value = 345/1000;
System.out.println(value);

it just prints 0.0 what the hell is the problem? i'm sure it is a sort
of f.cking cast problem but i've tried them all (also printf)

thanks
Tom Hawtin - 21 Apr 2007 16:09 GMT
> double value = 345/1000;

345 and 1000 are integers. / for integers rounds the value (towards
zero). 345 divided by 1000 is 0 remainder 345.

It probably is a bad idea that the same symbol is used to do different
things.

So use floating point literals:

double value = 345.0/1000.0;

Tom Hawtin
neuneudr@yahoo.fr - 21 Apr 2007 16:10 GMT
On Apr 21, 3:52 pm, bacrobi...@gmail.com wrote:
...
> double value = 345/1000;

345 / 1000 is performing, as per the Java Language Specifications,
an integer division...

double value = 345d / 1000;

will do what you want, so shall the following (why I prefer) :

double value = 345.0d / 1000;
Jussi Piitulainen - 21 Apr 2007 16:18 GMT
> i'm writing really frustrated by this stupid problem i try to print
> a double (or maybe float) variable with system.out.println but it
[quoted text clipped - 7 lines]
> it just prints 0.0 what the hell is the problem? i'm sure it is a
> sort of f.cking cast problem but i've tried them all (also printf)

Nothing to do with printing. The value really is zero. Division of
integer types truncates in Java and some other languages.

You have not tried all casts. Try these, for example:

 double value = 345/(double)1000;

 double value = ((double)345)/1000;

The straightforward thing to do is to write 345.0/1000.0, though.


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.