0

I am struggling to get a double value to set to the right number.

In the following code:

double d =  (double) (500 / 1000) / 9000;

d is set to 0.0.

I understand that doubles have limits and perhaps my problem is that I am exceeding the limits, but if I am is there a more appropriate way to store the result of this calculation?

Aziz12
  • 13
  • 4

2 Answers2

4

Change (500 / 1000) / 9000 to (500.0 / 1000) / 9000 in order to perform floating point division instead of int division. 500 / 1000 returns 0 while 500.0 / 1000 returns 0.5.

Eran
  • 387,369
  • 54
  • 702
  • 768
1

You are computing with ints try with doubles instead:

double d = (500.0 / 1000.0) / 9000.0;
Tristan Richard
  • 3,385
  • 1
  • 15
  • 17
  • @Ceelos you can't trigger float division in Java using only integers. at least one of the operands has to be float - either literally, or by cast. –  Feb 24 '16 at 19:20
  • why cast an integer literal to float instead of using explicit float literal? that makes completely no sense to me, apart inducing a brain overhead in understanding what the code actually does. –  Feb 24 '16 at 19:22
  • 1
    @Caelos if you cast an int to a double than you are no longer working with an int. int / int = int not a double... – Tristan Richard Feb 24 '16 at 19:22
  • @Ceelos that was not what you started saying. I do understand the concept but there is information loss by doing a cast. Giving me a -1 because I disagree is a bit childish. [link](http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.4) – Tristan Richard Feb 24 '16 at 20:39