Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double value returns 0 [duplicate]

Tags:

java

division

Here's an example:

Double d = (1/3);
System.out.println(d);

This returns 0, not 0.33333... as it should.

Does anyone know?

like image 416
oletk Avatar asked Dec 14 '08 06:12

oletk


People also ask

Is 0 a valid double?

The default value of a numerical data type is 0, so yes. There is positive and negative zero and x == 0 tests for both and will never give you an exception or error.

Which method returns value as double?

The doubleValue() method returns the double value represented by this object.

How do you know if a value is double or not?

Using the valueOf() method Similarly, the valueOf() method of the Double class (also) accepts a String value as a parameter, trims the excess spaces and returns the double value represented by the string. If the value given is not parsable to double this method throws a NumberFormatException.


2 Answers

If you have ints that you want to divide using floating-point division, you'll have to cast the int to a double:

double d = (double)intValue1 / (double)intValue2

(Actually, only casting intValue2 should be enough to have the intValue1 be casted to double automatically, I believe.)

like image 51
coobird Avatar answered Sep 25 '22 08:09

coobird


That's because 1 and 3 are treated as integers when you don't specify otherwise, so 1/3 evaluates to the integer 0 which is then cast to the double 0. To fix it, try (1.0/3), or maybe 1D/3 to explicitly state that you're dealing with double values.

like image 29
Firas Assaad Avatar answered Sep 25 '22 08:09

Firas Assaad