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

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.

Related

Converting String/Double to Int in Android

Hello new to android/Java,
I am using JSON to Parse values as strings and doubles. I am getting strings/doubles such as "6503.04" or "12.3942" etc. I am looking to see if I can convert these strings into an integer and also doubles into integers. I just need to get rid of the decimals points in the easiest way possible. How can I make that happen?
Any help appreciated.
double x = Double.parseDouble(your_string);
int y = (int) x;
y is going to have value of x with decimals cutted of.
Before casting to int you are able to floor or ceil the number if you want.
Don't forget that parsing functions usually throw an exception when your_string is not a number.
//get the value from json as double then get the integer
Double number = jsonObject.getDouble('longitude')
int newNumber = number.intValue()

How to remove decimal in java without removing the remaining digits

Is there any method to remove the . in java into a double value?
Example :
56.11124
to
5611124
I don't think there's a mathematical way to find out how many decimals there are in a double. You can convert to a String, replace the dot, and then convert it back:
Double.parseDouble(Double.toString(56.11124).replace(".", ""));
Be careful of overflows when you parse the result though!
Here's one way to do it,
First, convert the double to a string. Then, call replace to replace . with an empty string. After that, parse the result into an int:
double d = 5.1;
String doubleString = Double.toString(5.1);
String removedDot = doubleString.replace(".", "");
int result = Integer.parseInt(removedDot);
Obviously, this wouldn't work if the double's string representation is in scientific notation like 5e16. This also does not work on integral double values, like 5, as its string representation is 5.0.
doubles are inaccurate by nature. 5 and 5.0 are the same value. This is why you can't really do this kind of operation. Do you expect different results for a and b?
double a = 5;
double b = 5.0;
If you do, then you can't really do this, since there is no way of knowing what the programmer wrote exactly at runtime.
This might work
class Example {
public static void main(String[] args) {
double val = 56.1112;
while( (double)((int)val) != val )
{
val *= 10;
}
System.out.printf( "%.0f", val );
}
}
Output: 561112
This works by casting the double to int which truncates the floating information 56.11124 => 56. While the values aren't equal you multiply it by the base to push the . out. I don't know if this is the best way.
You can convert to BigDecimal and use the unscaledValue method:
BigInteger unscaled = new BigDecimal(myDouble).unscaledValue();
Depending on your intended output, you might also use BigDecimal#valueof(double) to create the intermediate BigDecimal.
Javadoc for BigDecimal#new(double)
Javadoc for BigDecimal#valueOf(double)
Javadoc for BigDecimal#unscaledValue()
You can convert it to a String and remove the . and convert it back to double something like
double value = 56.11124;
value = Double.valueOf(("" + value).replace(".", "")).doubleValue();
This will return 5611124.0 since its a double you will have the floating point. You can convert it to an int, but you have to take care of the possible overflow. Otherwise it would look like this
int normalized = (int) value;

Math floor mixing types error?

I have this:
String a = tonsescolhidos.getValue().toString();
int tons = Integer.parseInt(a);
float distlevel = 256/(tons - 1);
int temp;
temp = Math.floor(((float) (tons / distlevel) + 0.5)*distlevel);
tons = temp;
I get the error: "Incompatible types: possible lossy conversion from double to int" in the 5th line. How do i cast the variables in the right way.. what am I missing?
Math.floor only has one overload: double Math.floor(double). That always returns a double.
You would need to explicitly cast it to an int:
temp = (int) Math.floor(...);
But note that it is potentially lossy: double can store values too large to store in an int. So, you need to ensure that it's not a lossy operation by ensuring that the double's value is between Integer.MIN_VALUE and Integer.MAX_VALUE, by constraining the inputs appropriately.
Alternatively, rearrange your calculation so that you can do it all in integer math.

How to convert double to same value without decimal point

I want to remove the decimal point from double?
Ex: 234.567 will become 234567.
You can use String.valueOf method and then replace . with a blank character("").
String s = String.valueOf(234.567).replace(".","");
Use a easy way out.
Cast it to int. :P
x = (float) 5.12;
int a = (int) x;
System.out.println(a);

How to convert Float(Wrapper class) to Integer wrapper class?

how to convert Float to Integer in java?
Float value = 30.0F
how to convert above value to Integer?
Please help me?
Use Float.intValue():
Integer i = value.intValue();
Note that this causes autoboxing, but since you're planning to create an Integer anyway, this won't have any performance impact.
Note also that you should pay attention to rounding: intValue() and an int cast round toward zero. For rounding to the nearest integer, use Math.round(), for rounding down use Math.floor(), for rounding up use Math.ceil(). If you need some other kind of rounding, you need to implement it yourself.
Try this:
Float f = new Float(10.5);
Integer i = new Integer((int)Math.ceil(f));
f.intValue() is the way to go..
new Float(value).intValue() or simly cast it to int int v = (int) value
You can just do this:
Float value = 30.0f;
Integer intVal = value.intValue(); // auto-boxing happens here
Use value.intValue() method.
Float value = 30.0F;
Integer intValue=Integer.valueOf(value.intValue());

Categories

Resources