0

I made an app in Java with libGDX. I need to use the proportion of the screen's height and 1080. So I created a float called rh which equals Gdx.graphics.getHeight()/1080

float rh = (Gdx.graphics.getHeight()/1080);

In my case my screen's height is 1200 pixels. So in my case rh should be 1.111111... But rh becomes 1. If the screen's height is lower than 1080 pixels, then rh is 0. Why is this happening what could I do?

Please help! Thanks in advance.

P.S: Gdx.graphics.getHeight() gets the height of the screen in nr of pixels.

zbarni
  • 129
  • 2
  • getHeight() returns an int, and 1080 is, by default, an int value. So you must cast the ints to floats in order to get a float answer, otherwise the answer will be rounded down. – cschieb Dec 09 '14 at 18:09
  • The reason is that you are performing integer division. You need a floating point number to get what you are looking for. See @Sarthak Mittal's example below. – zack.lore Dec 09 '14 at 18:09
  • Gdx.graphics.getHeight() returns an integer, and 1080 is treated as integer.... so java rounds it. :) Sarthak's answer would give you do the job since he is turning the integer into a float using a cast – bakriawad Dec 09 '14 at 18:11

2 Answers2

10

Try this:

float rh = (Gdx.graphics.getHeight()/(float)1080);

The problem is that the getHeight() method of yours would return an int and when java divides two integers, the result is an int, after that, java initializes that value to the variable present at the left hand side.

Sarthak Mittal
  • 4,639
  • 2
  • 19
  • 41
7

When you divide two ints, a division of integers is performed, and the result is an int. If you store the result in a float/double variable, it is cast to float/double but the value is still int (i.e. there is no fraction).

In order to perform a floating point division, at least one of the numbers you are dividing must be a float or double. If both are int, you can cast one of them :

float rh = Gdx.graphics.getHeight()/(float)1080;

or

float rh = (float)Gdx.graphics.getHeight()/1080;

or without casting

float rh = Gdx.graphics.getHeight()/1080.0;
Eran
  • 359,724
  • 45
  • 626
  • 694