Android Studio not calculating float value...or am I dumb? [duplicate] - java

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?

Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);

If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;

(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.

Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)

String.format("%2.02f", (float)totalOptCount/totalRespCount);

to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));

Related

Java data types [duplicate]

This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
If you are using int values, using a double may be a better choice and have less rounding error. float can represent int values without error up to ~16 million. double can accurately represent all int values.
double percentage =(double) totalOptCount / totalRespCount;
Percentages are usually multiplied by 100, meaning you can drop the cast.
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
here both dividend and divisor are of type int which means they will allow only integer values and the answer of such equation will always be an integer literal.
if I break this it will be something like below
(double)(500/1500)
According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int
(double)(0)
Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result
0.0
and then you can change the result to any format as suggeted by #Zach Janicki.
keep in mind if both the operands are of same type than result will be of same type too.
Integer division (which includes long, short, byte, char, int) in Java always returns an int (or long, if one of the parameters is long), rounding towards zero. Your conversion occurs after this calculation.
(The formatting question is already answered by the other answers - alternatively you could also have a look at java.text.NumberFormat, specially java.text.DecimalFormat.)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
to format a double and print out as a percentage, you can use use
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));

Java integer-double division confusion [duplicate]

This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 7 years ago.
Program 1
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
VS.
Program 2
int sum= 30
double avg =sum/4.0 // Prints lns 7.5
Is this because the '4' in program 1 is acting as a literal integer? so 30/4 would give me 7. However since this data type is a double, we need to add a .0 to end. so '7.0'
Program 2 has 4.0 which is acting as a literal double. an int/double would always give double because it more precise. so we get '7.5'. I don't understand what double data type is doing to the result though.. it really doesn't need to do anything since the conditions of the double data type are already satisfied.(have the most precise result out of the computation).
Am I wrong? I encourage you to correct me! This is how I learn.. :)
In your first example:
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
sum is an int, and 4 is also an int. Java is dividing one integer by another and getting an integer result. This all happens before it assigns the value to double avg, and by then you've already lost all information to the right of the decimal point.
Try some casting.
int sum = 30;
double avg = (double) sum / 4; // result is 7.5
OR
int sum = 30;
double avg = sum / 4.0d; // result is 7.5
This is an integer division (because it involves two integers)
int sum = 30;
double avg = (sum / 4); // result is 7
Integer division, will round down to the nearest integer.
However, this is a double division (because 4.0 is a double)
int sum= 30
double avg = (sum/4.0) // result is 7.5
This is the expected behaviour, and the conversion are all well defined. No need to guess. Take a look at the java docs about conversion.
A widening conversion of an int or a long value to float, or of a long
value to double, may result in loss of precision - that is, the result
may lose some of the least significant bits of the value. In this
case, the resulting floating-point value will be a correctly rounded
version of the integer value, using IEEE 754 round-to-nearest mode
In java, operations involving only integer types (int, long and so on) have integer results. This includes divisions.
Both 30 and 4 are integer values, so if you try to divide them, integer division is used.
But if you try either 30.0/4 or 30/4.0 then the result will be 7.5 because you will be using floating-point division.
The declared type of the variable avg has no influence on the result. The decimal part is lost during the division, and not when you assign the value to the variable.
Image taken from : http://www.mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/mixed.html
Refer above URL for more clear explanation.
PROGRAM 1
In Java, when you do a division between two integers, the result is an integer. So when you do sum/4, the result is the integer 7. Then you assign that integer to a double variable, so that 7 turns into 7.0.
PROGRAM 2
In Java, when you do a division between an integer and a double, the result is a double. So when you do sum/4.0, the result is the double 7.5. Then you assign that to a double variable, so it's still 7.5.
So the problem is not how println prints the variables, but how division works in Java

How to make any double datatype into 0.00 (2 digits after decimal point) format taking in another double datatype (Android/Java)? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
I'm beginner in android developing. How can I make a double datatype i.e 56.32534 into 56.33? But I want to take it in a double variable. I know a way but it takes in String.
Double value = 56.32534;
DecimalFormat df = new DecimalFormat("0.##");
String newvalue = df.format(value);
Here, newvalueis a string. But I want to take it in a double datatype.
I need to use it's numeric value not just in display purpose only.
You can use Math.round():
double value = 56.32534;
double rounded = Math.round(100 * value) / 100.0;
The multiplication and then division by 100 is necessary because Math.round() rounds to the nearest long value.
If you want to generalize this to a variable number of digits, you can use something like this:
public double round(double value, int digits) {
double scale = Math.pow(10, digits);
return Math.round(value * scale) / scale;
}
This will even work if digits is not positive; it will round to the nearest integer if digits is 0, to the nearest 10 if digits is -1, to the nearest 100 if digits is -2, etc.
We need a little bit more precision on what you want to do. Do you want to display it that way or just use its numerical value that way ?
If it's the display your solution is ok. You could always get back the float number from the string afterwards.
On the other hand if you want to use it as a numerical value what you could do is
double rounded = (double) Math.round(myfloat * 100) /100;
I think it works. Can't test it as I'm on my mobile though

Java float not acting correctly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why does (360 / 24) / 60 = 0 … in Java
I am having this problem:
float rate= (115/100);
When I do:
System.out.println(rate);
It gives me 1.0
What... is the problem?
115 and 100 are both integers, so will return an integer.
Try doing this:
float rate = (115f / 100f);
You're performing integer division (which provides an integer result) and then storing it in a float.
You need to use at least one float in the operation for the result to be the proper type:
float rate = 115f / 100;
float rate= (115/100);
Does the following things:
1) Performs integer division of 115 over 100 this yields the value 1.
2) Cast the result from step 1) to a float. This yields the value 1.0
What you want is this:
float rate = 115.0/100;
Or more generally, you want to convert one of the pieces of your division into a float whether that is via casting (float)115/100 or by appending a decimal point to one of the two pieces or by doing this float rate = 115f / 100 is completely up to you and yields the same result.
In order to perform floating-point arithmetic with integers you need to cast at least one of the operands to a float.
Example:
int a = 115;
int b = 100;
float rate = ((float)a)/b;
use float rate= (float)(115.0/100); instead
It is enough to put float rate = 115f / 100;
The problem you have is that your dividend and divisor are declared as integer type.
In mathematic when you divide two integer results only with remainder. And that is what you assign to your rate variable.
So to have the result as you expected, a remainder with fraction (rational numbers). Your dividend or divisor must be declared in a type with precision.
Base two known types with precision are float (Floating point) and double (Double precision).
By default all numbers (integer literals for purists) written in Java code are in type int (Integer). To change that you need to tell the compiler that a number you want to declare should be represent in different type. To do that you need to append a suffix to integer literal.
Literals for decimal types:
float - f or F; 110f;
double - d or D 110D;
Note that when you would like to use the double, type you can also declare it by adding a decimal separator to literal:
double d = 2.;
or
double d = 2.0;
I encourage you to use double type instead of float. Double type is more suitable for most of modern application. Usage of float may cause unexpected results, because of accuracy problem that in single point calculation have bigger impact on result. Good reading about this “What Every Computer Scientist Should Know About Floating-Point Arithmetic”.
In addition on current CPU architecture both float and double have same performance characteristic. So there is not need to sacrifice the accuracy.
A final note about floating point types in is that non of them should be use when we write a financial application. To have valid results in this matter, you should always used [BigDecimal]

Error with division using double type in Java

Okay. I have been bashing my head against the wall for like 2 hours now trying to figure out why in the world double answer = 364/365; is telling me that answer is 0. Or any other combination of double for that matter, its just truncating the decimal and I just don't know why.
364/365 performs integer division (truncates the decimal).
Try double answer = 364.0/365; to force it to perform floating point division.
Something like:
double days_in_year = 365;
double answer = 364/days_in_year;
would work as well, since one of the operands isn't an integer.
You're taking an int type (364) and dividing by another int type (365) - the answer is going to be an int. This is then stored in a double type answer. You could do the following:
double answer = 364d / 365d;
More info here:
http://mindprod.com/jgloss/division.html
You need do do double division. Right now Java is interpreting it as integer division and returning the truncated int.
What you need is:
double answer = 364 / 365.0;
or
double answer = 364 / (double) 365;
The reason is that the default type of integer literals in java is int and all the result of all int based arithemetic is type casted back to int. Hence though your answer is 0.997, when it is typecasted back it becomes 0:
(int)0.997 = 0
So you can do like this:
364.0/365.0
or
((float)364)/365
All the above answers are right, would just like to add that it is all about GIGO.
double answer = 364/365;
in above code double type implies only to answer variable and arithmetic expression has both operands of int type. So the output of the arithmetic expression is also int type which is then through auto up-casting to double type gives output 0.0, just like below examples:
double ans = 4.0/0;
the above code will give output Infinity as one of the operand is Floating-point number so through auto type-casting 0 is converted to 0.0 and the result is as per the Floating-point datatype.
whereas
double ans = 4/0;
will give java.lang.ArithmeticException: / by zero exception at runtime since both the operands are of datatype int and so the output is as per the Integer datatype irrespective of ans variable datatype being double.

Categories