stupid problem with variable showing

B

bacrobidia

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 fucking cast problem but i've tried them all (also printf)

thanks
 
T

Tom Hawtin

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
 
N

neuneudr

On Apr 21, 3:52 pm, (e-mail address removed) 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;
 
J

Jussi Piitulainen

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 fucking 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,281
Latest member
Pedroaciny

Latest Threads

Top