JamesV.
JamesV.

Reputation: 55

How Do I Convert from int to float?

I am tasked with creating a program that rounds a number such as 2.7 to 3 and 2.5 to 2. I have already written a code that does this but my teacher wants the output in int. (i.e. 2.7 = 3). Here is what I have:

   import java.util.*;
   import java.util.Scanner;
   public class HandsOn14JamesVincent {
       public static void main(String[] args){
           Scanner input = new Scanner(System.in);
           System.out.println("Enter a decimal number and I will round it."); 
           float num = input.nextFloat();
           float num1 = Math.round(num);
           float num2 = num1 - num;
           if (num2 <= .3)
           System.out.println(Math.ceil(num));
           if (num2 > .3) 
           System.out.println(Math.floor(num));
       } 
   }

It displays the correct number, but it displays them in float (2.0). I can't seem to figure out how to convert them. I tried multiplying the num by (int) but it didn't work. Please Help!!

Upvotes: 1

Views: 308

Answers (2)

Fiat Lux
Fiat Lux

Reputation: 13

To solve this problem I created a float var call numF so i give num to numF float numf = num then I use the numF with the same value of num in meth operations

Upvotes: 0

Wilmer SH
Wilmer SH

Reputation: 1417

James you can cast a float to an int and it will drop the decimal part of the number.

   import java.util.*;
   import java.util.Scanner;
   public class HandsOn14JamesVincent {
       public static void main(String[] args){
           Scanner input = new Scanner(System.in);
           System.out.println("Enter a decimal number and I will round it."); 
           float num = input.nextFloat();
           float num1 = Math.round(num);
           float num2 = num1 - num;
           if (num2 <= .3)
           System.out.println((int)Math.ceil(num));
           if (num2 > .3) 
           System.out.println((int)Math.floor(num));
       } 
   }

Notice the (int)

Upvotes: 1

Related Questions