Lets say that I have variable tmp which is a double, and I want to convert tmp to an int, but still have the variable called tmp. How would I do this? Thanks
Asked
Active
Viewed 173 times
-2
-
possible duplicate of [Rounding a double to turn it into an int (java)](http://stackoverflow.com/questions/2654839/rounding-a-double-to-turn-it-into-an-int-java) – DreadHeadedDeveloper Oct 28 '14 at 15:10
-
This is a duplicate question to many others on this site, please google your questions or look them up on this site before posting a question – DreadHeadedDeveloper Oct 28 '14 at 15:11
-
1Why do you want to still have the variable called tmp? You'll have to assign this int value to another variable as `tmp` is declared as `double` and not `int`. – user2336315 Oct 28 '14 at 15:11
-
I was just wondering if there was any way to convert the type of a variable without using another variable. I have looked through the site and online, and have not found an answer to that question. – Oct 28 '14 at 15:14
-
@user2336315 is correct, it would be best that you store your double into a different variable then declare tmp as an int and follow the links posted to figure out how to convert – DreadHeadedDeveloper Oct 28 '14 at 15:14
1 Answers
0
You can't have the same variable as both an int
and a double
.
You can have this though:
double d = 0.1d;
int i = (int) d;
d = (double) i;
System.out.println(d);
Basically you first cast your double
to an integer
, losing the fraction. Afterwards you cast it to a double
again and assign it to your d
variable. You don't have to explicitly do the casting from int
to double
because it is a widening conversion, but it makes it more clear what happens.
The end result is that your d
variable now has a value that can be precisely interpreted by an integer but on the other hand you also, well, basically threw away your fraction. Your variable did not change its type, however.
You can write this less verbosely like this:
double d = (int) 0.1d;

Jeroen Vannevel
- 43,651
- 22
- 107
- 170