-4

have a decimal float from a user input calculation, say 2.856 that I need to turn into the integer 2.

Note, this has to be done in the code itself and cannot simply be output with %.0f; I need it for future calculations.

Additional Note, I have used

float Var1;
int Var2;
Var1 = 2.856;
Var2 = (int)Var1;

And if this is the easiest way to do it, please explain how (int) works, because I have no idea.

EDIT: Okay, so I was a little unclear in my explination, Var 1 = 2.856 is already determined by the code. I don't actually type out any numbers here; so using that I need to turn Var1 into Var2. So I can't type in code

Var2=(int)2.856

because 2.856 changes all the time. Can I do

Var2=(int)Var1?

Or anything to that extent?

3 Answers3

0

You have to put an f after the number, so it's treated as a float and not as a double:

var1 = 2.856f;

then cast it to a int:

var2 = (int)var1;

(int) number: This is called casting (can be made with other primitive types, also with classes). When casting a number to int, it get rid of the non-integer part (after the dot), and just returns the integer part.

Note: I would recommend you to follow Java naming conventions. Your variables should be named like nameOfVariable, while classes should be named like NameOfClass.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0
float f = 2.345F;
in i = (int) f;

It's as easy as that. And yes, if this wasn't clear; you are required to place an F behind the value for floating-point numbers, otherwise it will be interpreted as a double.

Reinstate Monica
  • 2,767
  • 3
  • 31
  • 40
0

That is indeed the easiest way to do it. What (int) does is "cast" the float variable to an integer form. Since float variables cannot be stored as integers normally due to the decimal point, the (int) "casts" the float to an integer by truncating the decimal part away. Since you're working in java, it's also a good idea to follow java naming conventions, which in this case means you should start your variable names with lowercase letters.

Iburi Noc
  • 56
  • 3