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.