简体   繁体   中英

Java - how to quickly convert variable integer -> float?

I am newbie in Java and just trying to convert a variable according to math operation. Let's have following scheme:

int var_result;
if(addition) {
  var_result = number1+number2; // number1, number2 => integers
}
else if(division){
  var_result = (float) number1 / number2;
  // and here is the problem - I don't know, how to convert "var_result" from integer to float
}

...just print var result ...

Is there any quick way, how to convert the var_result variable in this case? The easiest way in this example would be don't convert it and just use float var_result_float , but I don't want to solve it this way...

Thanks

int var_result; is already declared. You can't expect to store a float in it, without losing precision.

When you perform type-casting, the variable is temporarily treated as another type for the purpose of evaluation of an expression but that does not change what it actually is.

An int remains an int. You should go with float var_result_float to store a float.

int var_result is an int variable.
If you need a float use a float var_result

I don't want to solve it this way...

Well...This is the only way.

If you need to store an int or float in a variable you can use a double to store all possible values.

IMHO Don't use a float if you can possibly avoid it as its precision is fairly poor.

You can't change type of variable, but you can get what you want this way:

Object var_result; 
if(addition) { 
  var_result = new Integer(number1+number2); // number1, number2 => integers 
} 
else if(division){ 
  var_result = new Float( (float) number1 /  (float) number2); 
} 

Of course to use the number, you have to test the type with instanceof and do cast to Float or Integer as needed, so this is very clumsy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM