1

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!!

3
  • Shouldn't you be comparing to 0.5 not to 0.3? And can't you just cast to an int? (int) floatingPointNumber Commented Apr 6, 2016 at 17:55
  • I have to use .3 so a number such as 1.7 rounds up, and and a number such as 1.6 rounds down. That's what the assignment is. Commented Apr 6, 2016 at 17:59
  • FWIW, (int)num is not called multiplying with (int), it is called casting to int. Commented Apr 6, 2016 at 19:43

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

Granted, the question title is misleading. The OP wants to convert a float to an int (and not the other way round, as stated in the question title). Nonetheless, how does assigning a float variable to another float variable convert it to an int?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.