1

I am trying to have this code convert inches to feet, but whenever I try and get an output I find it is rounded down even though I am returning it as a float.

I have tried changing the code to do the modulus function + the division function, but the only gave the remainder. I am new to code so this is probably really easy just can't seem to figure it out.

``````````````````JAVA````````````````````````````````` //this is the method that I using to output.

public static void main(String[] args) {
    System.out.println(calcFeetAndInchesToCentimeters(34));
}

//this is the method I am actually using to calculate.

public static float calcFeetAndInchesToCentimeters(int inches){
    if(inches >= 0){
        return inches / 12;
    }else{
        return -1;
    }
 }

output: 2.0



I would like to have the output be when I run the code above 2.83, however,​ I am only getting the rounded down version. I am not trying to find a 

3 Answers3

1

you can cast integer to float and then try

public static float calcFeetAndInchesToCentimeters(int inches){
    if(inches >= 0){
        return (float)inches / 12;
    }else{
        return -1;
    }
 }
0

You are passing an integer to the method and dividing by an int so the result will always be an int. To fix this just change your method to:

    public static float calcFeetAndInchesToCentimeters(float inches){}
Nexevis
  • 4,647
  • 3
  • 13
  • 22
0

Typecast inches to float and then divide.

public static float calcFeetAndInchesToCentimeters(int inches) {
    if (inches >= 0) {
        return ((float) inches) / 12;
    } else {
        return -1;
    }
}
Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
Rahul Vedpathak
  • 1,346
  • 3
  • 16
  • 30
  • Thank you so much! I knew it was something simple, but right now there is just so much new info I can't remember everything. – Jacob Warren May 15 '19 at 18:34