Here's an example:
Double d = (1/3);
System.out.println(d);
This returns 0, not 0.33333... as it should.
Does anyone know?
-
That's because
1
and3
are treated asintegers
when you don't specify otherwise, so1/3
evaluates to theinteger
0
which is then cast to thedouble
0
. To fix it, try(1.0/3)
, or maybe1D/3
to explicitly state that you're dealing with double values. -
Wow, thank you!
But how about if i have:
double d = (height/imageHeight)*imageWidth;
What would I use on that? Double.valueOf() or something else?
tvanfosson : Then just use a simple cast of one of the variables in the division: double d = ((double)height/imageHeight)*imageWidth;chriscena : Please add additional comments and questions as comments to the related answer and not as a separate answer to you question.recursive : Try double d = height*imageWidth/imageHeight; -
If you have
int
s that you want to divide using floating-point division, you'll have to cast theint
to adouble
:double d = (double)intValue1 / (double)intValue2
(Actually, only casting
intValue2
should be enough to have theintValue1
be casted todouble
automatically, I believe.) -
And thank you too! Problem solved :)
-
Use double and not Double unless you need to use these values in the object sense. Be aware about the Autoboxing concepts
0 comments:
Post a Comment